Skip to content

Instantly share code, notes, and snippets.

@wosephjeber
Created November 29, 2023 21:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save wosephjeber/7fae46067574abeb6963ee025b468481 to your computer and use it in GitHub Desktop.
[WIP] An RTL-like `waitFor` utility, without the DOM stuff
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