setTimeout happens only once in a loop expression

后端 未结 7 1252
耶瑟儿~
耶瑟儿~ 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-25 00:04

    It is because setTimeout() function is non-blocking. Therefore your setTimeout() function is running only first time.

    Try this code...

    var i = 1;
        function func1(){
            setTimeout(function(){
                doSomething();
                i++;
                if(i < 10){
                    func1();
                }
            }, 3000);
        }
    func1();
    

提交回复
热议问题