I am working on a countdown timer written in Javascript. Fairly basic really. Just uses setInterval for the timing aspect. I wrote it using the prototype method of storing functions and variables so I can create a “class”.
I call the code in this fashion.
function testTimer() {
var newTimer = new CDTimer($("#voteTimer"),30,"");
newTimer.start();
}
When the below code runs, console.log is printing out undefined or NaN.
function CDTimer (target, duration, callback) {
this.target = target;
this.duration = duration;
this.callback = callback;
}
CDTimer.prototype.start = function() {
this.start = new Date().getTime();
this.interval = setInterval(this.update, 1000);
}
CDTimer.prototype.update = function() {
console.log(this.duration, this.start);
this.elapsed = this.duration - (new Date().getTime() - this.start) / 1000
if (this.elapsed < 0) {
clearInterval(this.interval);
this.callback();
}
else {
console.log(this.elapsed);
$(this.target).text(this.elapsed);
}
}
CDTimer.prototype.stop = function() {
clearInterval(this.interval);
}
I must be missing something silly. What is happening to my variables and their values?
Thanks for the insight.
The function called from
setIntervalis provided athiswhich is the window, not the timer.You may do this :
Note that the MDN offers a detailed explanation.
EDIT following comment : if you don’t want to create a new variable in the start function, you could do this :
But I’m not sure the readibility is improved by this move of the variable creation and it’s not compatible with IE (if you don’t patch it, see MDN’s solution).