Reputation: 5361
loading = setTimeout(function(){$("#myDiv").html('3');},1500)
loading = setTimeout(function(){$("#myDiv").html('2');},2500)
loading = setTimeout(function(){$("#myDiv").html('1');},3500)
loading = setTimeout(function(){$("#myDiv").html('Go!');},4500)
I have that code for example which counts down until something starts. But if a user clicks a button called "Stop" I want the countdown to stop. I am aware of the clearTimeout and I have used clearTimeout(loading) but this does not work. I believe it's because loading is redefined a second later.
Thanks
Upvotes: 2
Views: 133
Reputation: 2224
With setInterval, you will be able to actually pause the timer (which is impossible with setTimeout):
var previousTime = Date.now();
var elapsed = 0;
var stop = false;
var step = 3;
var timer = setInterval(function(){countdown()},100);
var countdown = function() {
if (!stop) {
elapsed += Date.now() - previousTime;
}
previousTime = Date.now();
if (elapsed >= 1500 && step == 3) {
$("#myDiv").html('3');
step--;
}
else if (elapsed >= 2500 && step == 2) {
$("#myDiv").html('2');
step--;
}
else if (elapsed >= 3500 && step == 1) {
$("#myDiv").html('1');
step--;
}
else if (elapsed >= 4500 && step == 0) {
$("#myDiv").html('Go!');
step = 1000;
clearInterval(timer);
}
}
$("#stop").click(function(e) {
e.preventDefault();
stop = true;
});
Upvotes: 2
Reputation: 442
Clicking stop should set a boolean, which you can check for in each setTimout
function before changing the HTML.
var loading = [],
mydiv = document.getElementById("myDiv"),
stopped = false;
function countdown(number){
if(!stopped){
mydiv.innerHTML = number;
}
}
loading[0] = setTimeout(function(){countdown("3")},1500);
loading[1] = setTimeout(function(){countdown("2")},2500);
loading[2] = setTimeout(function(){countdown("1")},3500);
loading[3] = setTimeout(function(){countdown("0")},4500);
$("#stop").on("click", function(e){
e.preventDefault();
stopped = true;
});
Find the JSFiddle here.
Upvotes: 0
Reputation: 199
clearTimout wasn't working because you are reusing 'loading' variable. Try this:
loading1 = setTimeout(function(){$("#myDiv").html('3');},1500);
loading2 = setTimeout(function(){$("#myDiv").html('2');},2500);
loading3 = setTimeout(function(){$("#myDiv").html('1');},3500);
loading4 = setTimeout(function(){$("#myDiv").html('Go!');},4500);
$("#stop").click(function(e) {
e.preventDefault();
clearTimeout(loading1);
clearTimeout(loading2);
clearTimeout(loading3);
clearTimeout(loading4);
});
Upvotes: 5