setTimeout in Node.js loop

后端 未结 8 1620
眼角桃花
眼角桃花 2020-12-06 05:16

I\'m a bit confused as to how setTimeout works. I\'m trying to have a setTimeout in a loop, so that the loop iterations are, say, 1s apart. Each l

8条回答
  •  无人及你
    2020-12-06 05:53

    setTimeout is non blocking, it is asynchronous. You give it a callback and when the delay is over, your callback is called.

    Here are some implementations:

    Using recursion

    You can use a recursive call in the setTimeout callback.

    function waitAndDo(times) {
      if(times < 1) {
        return;
      }
    
      setTimeout(function() {
    
        // Do something here
        console.log('Doing a request');
    
        waitAndDo(times-1);
      }, 1000);
    }
    

    Here is how to use your function:

    waitAndDo(2000); // Do it 2000 times
    

    About stack overflow errors: setTimeout clear the call stack (see this question) so you don't have to worry about stack overflow on setTimeout recursive calls.

    Using generators (io.js, ES6)

    If you are already using io.js (the "next" Node.js that uses ES6) you can solve your problem without recursion with an elegant solution:

    function* waitAndDo(times) {
      for(var i=0; i

    Here is how to use your function (with co):

    var co = require('co');
    
    co(function* () {
      yield waitAndDo(10);
    });
    

    BTW: This is really using a loop ;)

    Generator functions documentation.

提交回复
热议问题