setTimeout happens only once in a loop expression

后端 未结 7 1255
耶瑟儿~
耶瑟儿~ 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: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)
    

提交回复
热议问题