I followed a tutorial for creating a JavaScript stopwatch and am trying to expand it to work with multiple stopwatches (multiple instances of a class). The problem I have is when I am trying to display the current value while the clock is ticking I need to hard code the class instance becasue using "this" doesn't work (on the line where I am using console.log). I have cut the code down to the minimum to try to understand this aspect, and have pasted what I have below:
function Timer(){
var time1 = null;
var time2 = null;
var timeLoop = null;
function getTime(){
var day = new Date();
return day.getTime();
}
this.start = function(){
time1 = getTime();
timeLoop = setInterval(function(){
time2 = getTime();
console.log(_Timer.duration());
//console.log(this.duration());
},500);
}
this.duration = function(){
return (time1 - time2) / 1000;
}
}
I think the link below describes my problem but I don't understand it enough to apply it here. Is the issue due to the owner being this.start rather than just this and how can I ammend the code to make it work with any instance of Timer?
http://www.quirksmode.org/js/this.html
I have included both the hard coded value line and the "this" line that doesn't work.
Thanks,
Geraint