I have this code -
function example() {
var i = 0;
function add() {
i++;
}
setTimeout(function doSomething() {
add();
setTimeout(doSomething, 1000);
}, 1000);
}
Now basically I want by a pressed on a button to make the "setTimeout" to stop - any ideas how may i do that? thanks for any kind of help
You need not to call setTimeout
inside setTimeout
. You can use setInterval
, it will call for every second. see below code to stop interval using clearInterval()
var timeInterval = '';
function example() {
var i = 0;
function add() {
i++;
}
//store time Interval using variable
timeInterval = setInterval(function() {
add();
//setTimeout(doSomething, 1000);-- remove this
}, 1000);
}
function buttonClick()
{
//clear time out
window.clearInterval(timeInterval);
}
You need to use clearTimeout:
var timer = setTimeout(doSomething, 1000); //store setTimeout in a variable
//now when you need clear it:
clearTimeout(timer)
To clear the the delay caused by "setTimeout" use "clearTimeout" function. Check Here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.