Skip to content

Instantly share code, notes, and snippets.

@keesey
Created July 23, 2022 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keesey/adb244aca5ea013160c811cfd7452636 to your computer and use it in GitHub Desktop.
Save keesey/adb244aca5ea013160c811cfd7452636 to your computer and use it in GitHub Desktop.
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