The setInterval will keep on executing the function until you stop it using the clearInterval() function, but to do that you need to assign a variable to the setInterval() function. The following code should do the work :
var counter = 0 ;
var interval;
function start_timer(){
interval=setInterval(increment_counter, 1000);
@akhil , unfortunately, it completely doesn’t solve the issue. There are 2 problems:
For eg, if the time i stopped the timer was 5 seconds, the next time i would start it would resume from there. It is fine if someone wants to use it as a pause and resume button. But, what if someone wants to use it as a resetr button?
If we press on the start interval button for the second time when the timer is still on, a) it’s speed doubles and b) if i stop the interval, it just slows down and does not stop.
The solution to problem no. 1 is easy , you just need to reset the value of your counter variable to 0 in the function.
As for problem no. 2 you’ll have to make sure that only one instance of setInterval() is running, and to do that just clearInterval() before you call the setInterval() function.
I’ll paste the JS code below so that its easier to understand :
var counter = 0 ;
var interval;
function start_timer(){
clearInterval(interval); //This will prevent the speeding up issue
interval=setInterval(increment_counter, 1000);
}
function increment_counter(){
counter_element = document.getElementById(“counter”) ;
counter_element.innerHTML = counter ;
counter= counter+1;
}
function stop_timer(){
document.getElementById(“counter”).innerHTML = “Timer over”;
clearInterval(interval);
counter=0; //This will reset the value of the counter to zero everytime to call this function
}
@akhil , that solves by problem but i did not understand how putting clearInterval(interval) solves the problem. I mean it works but can you explain its concept to me.
The reason we put that in front of the declaration of setInterval is to make sure that only one instance of setInterval is working. Multiple setInterval instances causes a lot of problem .Like what was happening to your code when the timer was sped up .So its there for safety measure just like how you’d make sure that switch is off before plugging in anything in the socket.