[英]javascript - making a setTimeout inside a setTimeout to stop
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? 现在基本上我想通过按下按钮来使“ setTimeout”停止-任何想法我该怎么做? thanks for any kind of help
谢谢你的帮助
You need not to call setTimeout
inside setTimeout
. 你不必调用
setTimeout
里面setTimeout
。 You can use setInterval
, it will call for every second. 您可以使用
setInterval
,它将每秒调用一次。 see below code to stop interval using clearInterval()
参见下面的代码,使用
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: 您需要使用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. 要清除“ setTimeout”引起的延迟,请使用“ clearTimeout”功能。 Check Here
在这里检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.