fe-notes icon indicating copy to clipboard operation
fe-notes copied to clipboard

实现带定时器的异步队列

Open Inchill opened this issue 3 years ago • 0 comments

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()

Inchill avatar Nov 01 '22 12:11 Inchill