Skip to content

Instantly share code, notes, and snippets.

@Teemwu
Last active December 30, 2021 07:03
Show Gist options
  • Save Teemwu/f5414c4dff29e7af1a166aad6712b931 to your computer and use it in GitHub Desktop.
Save Teemwu/f5414c4dff29e7af1a166aad6712b931 to your computer and use it in GitHub Desktop.
封装各种轮询
export default class Polling {
private timer: number
private interval: number
private times: number
constructor(interval = 5e3, times = -1) {
this.interval = interval
this.times = times
this.timer = 0
}
action(callback: () => Promise<any>, count = 0) {
const isPolling = this.times === -1 || (this.times >= 0 && count < this.times)
if (isPolling) {
const start = new Date().getTime()
callback().finally(() => {
this.clear()
if (isPolling) count += 1
const timeout = this.interval - new Date().getTime() + start
if (timeout <= 0) {
this.action(callback, count)
} else {
this.timer = window.setTimeout(() => this.action(callback, count), timeout)
}
})
}
}
clear() {
window.clearTimeout(this.timer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment