在foreach循环中中断setTimeout函数

时间:2016-08-11 19:56:54

标签: javascript jquery

我试图打破在页面加载时启动的setTimeout函数。所以我在这里做的是,如果我点击按钮然后我将标志值设置为true并且setTimeout应该打破这里没有发生的事情。 这个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);
                }); 

2 个答案:

答案 0 :(得分:2)

不是一次创建所有超时,而是仅在需要时创建它们。这样,当您决定停止时,您不必清除它们中的任何一个:

(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.

在您的代码版本中,您必须保留所有setTimeout次调用返回的 id 值,然后将它们全部(或至少其余的)传递给clearTimeout,一个接一个。这会使你的代码非常麻烦。我认为以上是一种更有效的方法。

答案 1 :(得分:0)

  

setTimeout无法从其回调本身停止。的setTimeout   返回一个timeoutId,可以传递给clearTimeout   停止那个特别计时器。

停止所有这些计时器的一种方法是创建一个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'sJavascript - wait until flag=true

相关问题