setTimeout not working inside forEach

前端 未结 2 1349
傲寒
傲寒 2020-12-24 12:11

I have a forEach that calls a function. There needs to be a delay between each time it is called. I\'ve put it inside a setTimeout inside the forEach. It isn\'t respecting t

2条回答
  •  清酒与你
    2020-12-24 12:35

    setTimeout is async. What it does is register a callback function and put it in background which will be triggered after delay. Whereas forEach is synchronous function. So what your code did is register callbacks "all at once" that each will be triggered after 5 seconds.

    Two ways to avoid it:

    Have an index to set the timer.

    json.objects.forEach(function(obj, index) {
        setTimeout(function(){
          // do whatever
        }, 5000 * (index + 1));
    });
    

    This way the delay factor is based on the index of your objects, so even you register them at same time, it will trigger based on their own delay. index + 1 to keep the same result as in question since it starts at 0.

    setInterval to loop your objects

    var i = 0;
    var interval = setInterval(function(){
        var obj = json.objects[i];
        // do whatever
        i++;
        if(i === json.objects.length) clearInterval(interval);
    }, 5000);
    

    setInterval is similar to setTimeout, although it triggers periodically based on interval. In here we access object and update the index inside of the interval function. Also don't forget to clear interval in the end.

    The difference between those two is setInterval only registered one function compare to setTimeout registered as many as number of items in the list.

提交回复
热议问题