[removed] setTimeout doesn't pause the loop

后端 未结 2 1878
误落风尘
误落风尘 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
    
    0 讨论(0)
  • 2021-01-27 02:07

    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
        }());
    }
    
    0 讨论(0)
提交回复
热议问题