setTimeout happens only once in a loop expression

后端 未结 7 1254
耶瑟儿~
耶瑟儿~ 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();
    
    0 讨论(0)
提交回复
热议问题