I was recently making a timer object and a ticking function that would tick every second according to a setTimeout loop. However, there was no delay in the ticking. If you try out the below code, you will find that the time number has increased to the thousands in only a few seconds. What, if anything, am I doing wrong?
<html>
<head>
</head>
<button onclick="startTimer()">Start</button>
<button onclick="stopTimer()">Stop Timer</button>
<button onclick="readTimer()">Read Timer</button>
<script>
function tick(){
console.log("TICK TOCK");
if(this.running == true){
this.time += 1;
console.log("HELLO!");
setTimeout(this.tick(), 1000, $(this));
}
}
function start(){
this.running = true;
this.tick();
}
function read(){
return this.time;
}
function stop(){
this.running = false;
}
function reset(){
if(this.running == false){
this.time = 0;
}else {
this.time = 0;
}
this.tick();
}
function timer(){
this.running = false;
this.time = 0;
this.start = start;
this.read = read;
this.stop = stop;
this.reset = reset;
this.tick = tick;
}
var t = new timer();
function startTimer(){
t.start();
}
function stopTimer(){
t.stop();
}
function readTimer(){
alert("This is the current Timer Reading: " + t.time);
}
</script>
</html>