Created
November 29, 2023 21:06
-
-
Save wosephjeber/7fae46067574abeb6963ee025b468481 to your computer and use it in GitHub Desktop.
[WIP] An RTL-like `waitFor` utility, without the DOM stuff
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 async function waitFor(callback, { timeout = 1000 } = {}) { | |
let intervalTimer; | |
let lastError = null; | |
let pending = false; | |
let timeoutTimer; | |
return new Promise((resolve, reject) => { | |
function onDone(result) { | |
clearInterval(intervalTimer); | |
clearTimeout(timeoutTimer); | |
pending = false; | |
resolve(result); | |
} | |
function onError(error) { | |
pending = false; | |
lastError = error; | |
} | |
timeoutTimer = setTimeout(() => { | |
clearInterval(intervalTimer); | |
reject(lastError); | |
}, timeout); | |
intervalTimer = setInterval(() => { | |
if (pending) return; | |
try { | |
const result = callback(); | |
if (result.then) { | |
pending = true; | |
result.then(onDone, onError); | |
} else { | |
onDone(result); | |
} | |
} catch (error) { | |
onError(error); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment