代码之家  ›  专栏  ›  技术社区  ›  paulsm4

如何在Javascript循环中每N次迭代休眠一次?

  •  2
  • paulsm4  · 技术社区  · 7 年前

    我目前有一个Javascript forEach()循环,但我需要更改代码,以便每500次迭代添加一个“sleep”。

    迭代:

    How do I add a delay in a JavaScript loop?

    for (let i=1; i<10; i++) {
        setTimeout( function timer(){
            alert("hello world");
        }, i*3000 );
    }
    

    我怎样才能在每第二次或每500次迭代中睡眠?

    附言:

    这个解决方案需要在Chrome和IE11上运行。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mark    7 年前

    您可以创建一个函数来捕获闭包中的循环变量,并返回一个简单函数,该函数带有一个按批大小返回的循环。这样做的效果是,它可以让您在停止的地方继续for循环。如果您有它返回一个布尔值,指示是否完成它,您可以将整个事情包装在一个 setInterval . 展示比解释更容易:

    function batch(batch_size, end){
        var i = 0                                  // capture i in closure
        return function(){
            for(i; i <= end; i++){
                console.log("doing something", i)  // work goes here
                if (!((i+1) % batch_size)) return i++
            }
            return false
        }
    }
    var f = batch(5, 11)                           // 0 - 11 batched in groups of 5
    if (f()){                                      // start immediately, then setInterval if not finished in one batch.
        var interval = setInterval(() => {
        f() ||  clearInterval(interval)
        }, 2000 )
    }
        2
  •  3
  •   Andy Ray    7 年前

    递归超时解决方案:

    const processInBatches = (array, limit, processFn, timeout) => {
        const batch = array.slice(0, limit);
        if(!batch.length) {
            return;
        }
        batch.forEach(processFn);
        const rest = array.slice(limit);
        setTimeout(() => processInBatches(rest, limit, processFn, timeout), timeout);
    }
    
    const array = ['a', 'b', 'c', 'd'];
    processInBatches(array, 2, (x) => console.log('processing',x), 1000);