setTimeout in Node.js loop

后端 未结 8 1600
眼角桃花
眼角桃花 2020-12-06 05:16

I\'m a bit confused as to how setTimeout works. I\'m trying to have a setTimeout in a loop, so that the loop iterations are, say, 1s apart. Each l

8条回答
  •  Happy的楠姐
    2020-12-06 05:58

            let i = 20;
            let p = Promise.resolve(i)
            while (i > 0) {
            (i => {
                p = p.then(() => {
                return new Promise(function (resolve, reject) {
                    setTimeout(function () {
                        console.log(i);
                    resolve()
                    }, 2000)
                })
                })
            })(i)
            i--
            }
            p = p.then(data => console.log('execution ends'))
    

提交回复
热议问题