JavaScript: setTimeout doesn't pause the loop

本秂侑毒 提交于 2019-12-02 05:21:45

You are continuously spawning multiple calls to process() immediately in the while and then telling process to wait 5 seconds before that callback happens.

// Run this loop over and over again
while (true) {
    // Create a function called process that process data
    var process = (function () {
        // Do something with data
        console.log("Something");
        // Wait a few seconds and do it again
        setTimeout(process, 5000);
    // This () right here says call process right now
    }());
}

when you run your code, while loop won't wait for setTimeout because it is async.

but you can do following to make your code work.

var p = 0;
var k = 0;
var now = new Date();
var code = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var index = 0; index < code.length; index++) {
    (function(idx, timeout){
        setTimeout(function(i) {
            //write your code herei
            console.log("printed after", (new Date() - now)/1000, " Seconds");

        }, timeout, idx);
        p++;
        if(p==5){
            p = 0;
            k += 5000;
        }
    })(index, k);
}

Following is the output

printed after 0.006  Seconds
printed after 0.008  Seconds
printed after 0.008  Seconds
printed after 0.008  Seconds
printed after 0.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!