setTimeout happens only once in a loop expression

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

    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)
    }
    
    
    

提交回复
热议问题