Created
May 29, 2023 10:04
-
-
Save crutchcorn/f57b557a2dd6239541edc62494ac963d to your computer and use it in GitHub Desktop.
Eww, a JS-only setTimeout polyfill??
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
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()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could
loop.then(resolve)
instead ofloop.then(() => resolve())
. Also goes forloop.resolve(cb)
.