Call Javascript Object Method with SetInterval() -


here fiddle.

i'm trying create countdown object uses moment.js (a plugin prefer on using date())

var countdown = function(enddate) {     this.endmoment = moment(enddate);      this.updatecountdown = function() {         var currentmoment, thisdiff;          currentmoment = moment();         thisdiff = (this.endmoment).diff(currentmoment, "seconds");          if (thisdiff > 0)             console.log(thisdiff);         else {             clearinterval(this.interval);             console.log("over");         }     }      this.interval = setinterval(this.updatecountdown(), 1000); } 

i create instance of countdown so:

var countdown = new countdown("january 1, 2014 00:00:00"); 

however function seems run 1 time. ideas? should using settimeout() instead?

you can either store this context local variable following:

var countdown = function(enddate) {   var self = this;   this.endmoment = moment(enddate);    this.updatecountdown = function() {       var currentmoment, thisdiff;        currentmoment = moment();       thisdiff = (self.endmoment).diff(currentmoment, "seconds");        if (thisdiff > 0)           console.log(thisdiff);       else {           clearinterval(self.interval);           console.log("over");       }   }    this.interval = setinterval(this.updatecountdown, 1000); } 

or can use variables directly such as:

var countdown = function(enddate) {   var endmoment = moment(enddate);    this.updatecountdown = function() {       var currentmoment, thisdiff;        currentmoment = moment();       thisdiff = (endmoment).diff(currentmoment, "seconds");        if (thisdiff > 0)           console.log(thisdiff);       else {           clearinterval(interval);           console.log("over");       }   }    var interval = setinterval(this.updatecountdown, 1000); } 

i prefer second approach - fiddle


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -