setTimeout happens only once in a loop expression

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

提交回复
热议问题