Execute function queue in javascript

后端 未结 6 680
误落风尘
误落风尘 2020-12-01 19:35

I\'m trying to create a function queue with several functions in it. After the creation i want to execute each function in it\'s turn. But these function have delayed instru

6条回答
  •  伪装坚强ぢ
    2020-12-01 20:06

    In order to make a clean queue, your asynchronous functions will need to somehow signify when they are done, or the next function won't know when to begin. This means you cannot pass in just any old function; they'll need to follow some format. I'd suggest taking a done callback as the first parameter in your function calls. This way, you can support both synchronous and asynchronous functions.

    var processQueue = function nextStep(queue) {
      var next = queue.shift();
      next && next(function() { nextStep(queue); });
    }
    
    function fun1(done) {
      setTimeout(function() {
        console.info('1');
        done();
      }, 1000);
    }
    
    function fun2(done) {
      console.info('2');
      done();
    }
    
    processQueue([fun1, fun2]);
    
    // >> 1 second wait
    // >> 1
    // >> 2
    

提交回复
热议问题