在foreach循环中打破setTimeout函数
问题描述:
我想破解在页面加载时启动的setTimeout函数。所以我在这里做的是,如果我点击按钮,然后我将flag值设置为true,并且setTimeout应该打破,而这不会发生在这里。 这个setTimeout函数在每个循环内部。以下是我的代码。在foreach循环中打破setTimeout函数
rData[0].dt.forEach(function(d, i) {
setTimeout(function() {
if(flag === "false"){
console.log(flag);
reserRadius(i); //here I am changing radius of circle
}else{
console.log(flag);
clearTimeout();
return;
}
}, i * 2000);
});
答
不是一次性创建所有超时,而只是在需要时创建它们。这样,您就不必清除任何人,当你已经确定停止:
(function repeat(list, i) {
if (i >= list.length) return; // nothing (more) to do
var d = list[i]; // do you need d at all??
setTimeout(function() {
if(flag === "false"){
console.log(flag);
reserRadius(i); //here I am changing radius of circle
repeat(list, i+1); // schedule next timeout only now.
}else{
console.log(flag);
// Don't schedule next timeout. This breaks the "loop".
}
}, 2000); // trigger 2 seconds from now. Note: no multiplying anymore.
})(rData[0].dt, 0); // pass initial values: the array and index.
在你的代码版本,你就必须保持ID所有setTimeout
调用返回值,和然后将它们全部(或至少剩下的)全部传递给clearTimeout
。这会让你的代码非常麻烦。我认为上述是一种更有效的方法。
答
setTimeout无法从其回调本身停止。 setTimeout 返回一个可以传递给clearTimeout的timeoutId,然后 停止该特定计时器。
停止所有这些定时器的一种方法是创建一个timeoutIds数组并进行如下更改。
var timerIds = [];
rData[0].dt.forEach(function(d, i) {
timerIds.push(setTimeout(function(){
if(flag === "false"){
console.log(flag);
reserRadius(i); //here I am changing radius of circle
}
else{
console.log(flag);
}
}, i * 2000));
});
function stopTimeouts(){
timerIds.forEach(function(id){
clearTimeout(id);
}
}
function codeThatMightChangeFlag(callback) {
// do a bunch of stuff
if (condition happens to change flag value) {
// call the callback to notify other code
stopTimeouts();
}
}
参见:Clear array of setTimeout's和Javascript - wait until flag=true
'clearTimeout'预计从'setTimeout'返回的ID,但如果你拥有了它没有任何意义,因为时间的函数被评为超时已经完成,没有理由调用'clearTimeout' –
目前还不清楚你确实想要你的代码做什么。你不能删除自己内部的'timeout',因为它在执行时已经被删除了。在你的问题中发布一个[JSFiddle](https://jsfiddle.net/)片段会很有用。 – 2016-08-11 20:04:10
我有这个setTimeout函数里面运行的动画代码。如果我将鼠标悬停在特定区域上,我希望这个动画停止,所以我正试图在按钮的帮助下停止它。 – shanky