Skip to content

实现带定时器的异步队列 #48

Description

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions