[removed] setTimeout doesn't pause the loop

后端 未结 2 1877
误落风尘
误落风尘 2021-01-27 01:29

I need to make some delays in my loop, every time after some amount of data (after a few cycles/iterations through my loop) is sent to the server.

Sending data and recei

2条回答
  •  无人及你
    2021-01-27 01:48

    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
    

提交回复
热议问题