How to create pause or delay in FOR loop?

前端 未结 12 1545
长情又很酷
长情又很酷 2021-02-01 19:57

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in for loop in javascript or

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 20:31

    The way I found was to simply use setInterval() to loop instead. Here's my code example :

    var i = 0;
    var inte = setInterval(() => {
        doSomething();
    
        if (i == 9) clearInterval(inte);
        i++;
    }, 1000);
    
    function doSomething() {
        console.log(i);
    };
    

    This loops from 0 to 9 waiting 1 second in between each iteration.

    Output :

    0 1 2 3 4 5 6 7 8 9
    

提交回复
热议问题