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.
thisto refer to? You havent created any objects using your constructors.