javascript - setInterval(): How to stop then start itself again? -


in if statement, want interval clear , call object function of again restart interval.

is such thing possible?

i tried way, i'm getting unexpected behavior. can see log keeps on logging every 200ms. while should have stopped since interval stopped , restarted , condition wouldn't evaluate true anymore.

datetime.prototype = {     start: function () {         var self = this;          sendajaxrequest(this.timeurl, function () {             var previoustime = new date().gettime();              this.tickintervalid = setinterval(function tick() {                 var currenttime = new date().gettime();                  if ((currenttime - previoustime) < 0) {                     console.log('you changed time backwards. restarting.');                      self.stop(); // <-- stopping                     self.start(); // <-- call same method running                      return;                 }                  self.dateelement.innerhtml = new date();                  previoustime = currenttime;                  return tick;             }(), 200);         });     },      stop: function () {         clearinterval(this.tickintervalid);          this.tickintervalid = null;     } } 

i think scope wrong setinterval call.

try change

this.tickintervalid = setinterval(function tick() { 

to use self

self.tickintervalid = setinterval(function tick() { 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -