setTimeout happens only once in a loop expression

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

    If you want iterate with constant delay, IMHO you better use setInterval:

    var loops = 9,
        intervalId = setInterval(function () {
            // My super code goes here
            console.log(loops);
            loops-- <= 0 && (clearInterval(intervalId));
        }, 3000);
    

    I've made a jsfiddle for you.

提交回复
热议问题