[英]javascript - making a setTimeout inside a setTimeout to stop
我有此代码-
function example() {
var i = 0;
function add() {
i++;
}
setTimeout(function doSomething() {
add();
setTimeout(doSomething, 1000);
}, 1000);
}
现在基本上我想通过按下按钮来使“ setTimeout”停止-任何想法我该怎么做? 谢谢你的帮助
你不必调用setTimeout
里面setTimeout
。 您可以使用setInterval
,它将每秒调用一次。 参见下面的代码,使用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);
}
您需要使用clearTimeout:
var timer = setTimeout(doSomething, 1000); //store setTimeout in a variable
//now when you need clear it:
clearTimeout(timer)
要清除“ setTimeout”引起的延迟,请使用“ clearTimeout”功能。 在这里检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.