fe-notes
fe-notes copied to clipboard
实现带定时器的异步队列
class Queue {
constructor () {
this.tasks = []
}
task (time, fn) {
this.tasks.push({ fn, time })
return this
}
async start () {
for (const item of this.tasks) {
const { fn, time } = item
await this.timeout(time).then(fn)
}
}
timeout (time) {
return new Promise(resolve => setTimeout(resolve, time))
}
}
new Queue()
.task(1000, () => console.log(111))
.task(2000, () => console.log(333))
.task(1000, () => console.log(444))
.start()