I know a million JavaScript timer questions have been asked already, but I can’t figure this one out.
The #drive element is updated the first time (to 0) but not after that, as if either setTimeout() is not working or this.count++ is not working. Anyone know why this isn’t working?
Thanks…
var timer = {
timerRunning: false,
count: 0,
delay: 1000,
tick: function() {
$("#drive").html(this.count);
this.count++;
setTimeout(function(){
if (this.timerRunning)
this.tick();
}, this.delay);
},
start: function() {
this.timerRunning = true;
this.tick();
},
stop: function() {
this.timerRunning = false;
}
};
timer.start();
The value of
thisinside yoursetTimeout()callback is no longer your timer object (it will be thewindowobject). That’s why it isn’t working.You can fix it like this by setting a closure variable to your object and using that instead: