Nested setTimeout alternative?

前端 未结 6 1575
逝去的感伤
逝去的感伤 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:58

    I think most simple way to do this is to create some closures within a function.
    First i'll recall that you have big interest in using setInterval, since the overhead of the setTimeout might have it trigger 10ms off target. So especially if using short (<50ms) interval, prefer setInterval. So we need to store the function array, the index of latest executed function, and an interval reference to stop the calls.

    function chainLaunch(funcArray, time_ms) {
      if (!funcArray || !funcArray.length) return;
      var fi = 0; // function index
      var callFunction = function () {
          funcArray[fi++]();
          if (fi==funcArray.length)
                  clearInterval(chainInterval);
       } ;
      var chainInterval = setInterval( callFunction, time_ms);
    }
    

    Rq : You might want to copy the function array ( funcArray = funcArray.slice(0); )
    Rq2 : You might want to loop within the array
    Rq3 : you might want to accept additionnal arguments to chainlaunch. retrieve them with var funcArgs = arguments.slice(3); and use apply on the functions : funcArray[fi++].apply(this,funcArgs);

    Anyway the following test works :

    var f1 = function() { console.log('1'); };
    var f2 = function() { console.log('2'); };
    var f3 = function() { console.log('3'); };
    
    var fArr = [f1, f2, f3];
    
    chainLaunch(fArr, 1000);
    

    as you can see in this fiddle : http://jsfiddle.net/F9UJv/1/ (open the console)

提交回复
热议问题