how to slow down a javascript loop

前端 未结 5 1105
执念已碎
执念已碎 2021-01-04 10:59

I would like a add a 1-2 second delay on each iteration of the following loop.




        
5条回答
  •  一生所求
    2021-01-04 11:32

    Modern JS Solution:

    function timeout(ms) {
        return new Promise(resolve => setTimeout(resolve, ms))
    }
    
    async function slowedCode() {
        console.log("Before Delay")
        await this.timeout(Math.random() * 2000 + 500) // Wait random amount of time between [0.5, 2.5] seconds
        console.log("After Delay")
    }
    
    async function slowedForLoop() {
        const data = ["1","2","3","4","5"]
        for (let d of data) {
            console.log(d)
            await this.timeout(Math.random() * 100 + 500)
        }    
    }
    

    The only draw back is you have to execute the delay from inside an async function.

提交回复
热议问题