Created
July 23, 2022 17:29
-
-
Save keesey/adb244aca5ea013160c811cfd7452636 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
const MAX_TIMEOUT = 2147483647; | |
class ChunkedTimeout { | |
private handle: number | undefined; | |
constructor(private callback?: () => void, private msLeft: number = 0) { | |
this.next(); | |
} | |
public clear() { | |
this.msLeft = 0; | |
if (this.handle) { | |
window.clearTimeout(this.handle); | |
delete this.handle; | |
} | |
} | |
private next() { | |
if (!(this.msLeft > 0)) { | |
this.clear(); | |
if (this.callback) { | |
this.callback(); | |
delete this.callback; | |
} | |
} else { | |
const ms = Math.min(MAX_TIMEOUT, this.msLeft); | |
this.msLeft -= ms; | |
this.handle = window.setTimeout(() => this.next(), ms); | |
} | |
} | |
} | |
const setTimeoutChunked = (callback: () => void, ms: number) => { | |
if (ms <= 0) { | |
callback(); | |
} else if (isFinite(ms)) { | |
if (ms <= MAX_TIMEOUT) { | |
const handle = window.setTimeout(callback, ms); | |
return () => window.clearTimeout(handle); | |
} | |
{ | |
const timeout = new ChunkedTimeout(callback, ms); | |
return () => timeout.clear(); | |
} | |
} | |
}; | |
export default setTimeoutChunked; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment