setTimeout happens only once in a loop expression

后端 未结 7 1253
耶瑟儿~
耶瑟儿~ 2021-01-24 23:35

This is an example:

function func1()
{
   setTimeout(function(){doSomething();}, 3000);
}
for(i=0;i<10;i++)
{
   func1();
}

after executing

相关标签:
7条回答
  • 2021-01-24 23:48

    With async.js:

    async.timesSeries(5, function (n, next) {
        setTimeout(function(){
            doSomething();
            next();
        }, 3000);
    });
    
    0 讨论(0)
  • 2021-01-24 23:52

    You are scheduling 10 calls, but the problem is all are getting scheduled for the same time, ie after 3 seconds.

    If you want to call them incrementally then you need to increase the delay in each call.

    A solution will be is to pass a delay unit value to the func1 like

    function func1(i) {
      setTimeout(function() {
        doSomething();
      }, i * 500);//reduced delay for testing
    }
    for (i = 0; i < 10; i++) {
      func1(i + 1);
    }
    
    var counter = 0;
    
    function doSomething() {
      snippet.log('called: ' + ++counter)
    }
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    0 讨论(0)
  • 2021-01-24 23:52

    The loop will schedule 10 timeouts all to be completed after 3 seconds. You can use recursion with setTimeout:

    function loopAsync(delay, n, f) {
      setTimeout(function() {
        if (n > 0) {
          f()
          loopAsync(delay, n - 1, f)
        }
      }, delay)
    }
    
    loopAsync(3000, 10, doSomething)
    
    0 讨论(0)
  • 2021-01-24 23:54

    What is heppening is that you are calling 10 times (without delay) func1() then what you have is 10 functions all on the same time, the solution is simple, use setInterval, here is a fiddle

    0 讨论(0)
  • 2021-01-24 23:54

    The for loop is running continuously so each call is 3000 millisecond of that call. Resulting in no delay between two calls. For better understanding, loop call func1 at time t and t + 1. So it will execute at t + 3000 and T + 3001 leaving no difference.

    You can try below approach :-

    function func1(i){
         setTimeout(function(){doSomething();}, i * 3000);
     }
    for(i=i;i<=10;i++){
      func1(i);
    }
    

    Note:- Loop intialized with i = 1.

    0 讨论(0)
  • 2021-01-24 23:57

    If you want iterate with constant delay, IMHO you better use setInterval:

    var loops = 9,
        intervalId = setInterval(function () {
            // My super code goes here
            console.log(loops);
            loops-- <= 0 && (clearInterval(intervalId));
        }, 3000);
    

    I've made a jsfiddle for you.

    0 讨论(0)
提交回复
热议问题