Skip to content

Instantly share code, notes, and snippets.

@crutchcorn
Created May 29, 2023 10:04
Show Gist options
  • Save crutchcorn/f57b557a2dd6239541edc62494ac963d to your computer and use it in GitHub Desktop.
Save crutchcorn/f57b557a2dd6239541edc62494ac963d to your computer and use it in GitHub Desktop.
Eww, a JS-only setTimeout polyfill??
globalThis.setTimeout = (cb, num) => {
const start = Date.now();
function loop() {
return new Promise((resolve) => {
queueMicrotask(() => {
const now = Date.now();
const diff = now - start;
if (diff < num) {
loop()
.then(() => resolve())
return;
}
resolve();
})
})
}
loop()
.then(() => cb());
}
@igor9silva
Copy link

You could loop.then(resolve) instead of loop.then(() => resolve()). Also goes for loop.resolve(cb).

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