Nested setTimeout alternative?

前端 未结 6 1577
逝去的感伤
逝去的感伤 2020-12-10 04:22

I need to execute 3 functions in a 1 sec delay.

for simplicity those functions are :

console.log(\'1\');
console.log(\'2\');
console.log(\'3\');
         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-10 04:45

    There is a new type of function declaration called generators in es6 (a.k.a ecmascript 6, es2015). It is incredibly useful for this situation, and makes your async code look synchronous. es6 is the latest standard of JavaScript as of 2015. It works on modern browsers but you can use Babel and its javascript polyfill to use generators now even on older browsers.

    Here is a tutorial on generators.

    The function myDelayedMessages below is an example of a generator. Run is a helper function that takes a generator function which it calls and provides a function to advance the generator as the first argument of the generator function that it called.

    function delay(time, callback) {
          setTimeout(function () {
            callback();
          }, time);
    }
    
    function run(generatorFunction) {
      var generatorItr = generatorFunction(resume);
      function resume(callbackValue) {
        generatorItr.next(callbackValue);
      }
      generatorItr.next()
    }
    
    run(function* myDelayedMessages(resume) {
      for(var i = 1; i <= 3; ++i) {
        yield delay(1000, resume);
        console.log(i);
      }
    });

    This is an overview of the code which is similar to the above tutorial's final overview.

    1. run takes our generator and creates a resume function. run creates a generator-iterator object (the thing you call next on), providing resume.
    2. Then it advances the generator-iterator one step to kick everything off.
    3. Our generator encounters the first yield statement and calls delay.
    4. Then the generator pauses.
    5. delay completes 1000ms later and calls resume.
    6. resume tells our generator to advance a single step.
    7. Our generator continues from the spot it yielded at then console.logs i, which is 1, then continues the loop
    8. Our generator encounters the second call to yield, calls delay and pauses again.
    9. delay waits 1000ms and ultimately calls the resume callback. resume advances the generator again.
    10. Our generator continues from the spot it yielded at then console.logs i, which is 2, then continues the loop.
    11. delay waits 1000ms and ultimately calls the resume callback. resume advances the generator again.
    12. Our generator continues from the spot it yielded at then console.logs i, which is 3, then continues and the loop finishes.
    13. There are no more calls to yield, the generator finishes executing.

提交回复
热议问题