Last active
December 30, 2021 07:03
-
-
Save Teemwu/f5414c4dff29e7af1a166aad6712b931 to your computer and use it in GitHub Desktop.
封装各种轮询
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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