I was working on a content script for a Chrome Extension, and I needed to wait until a certain element appeared in the DOM that I don’t control, or timeout.
I couldn’t find anything that suits my need, so I came up with this async function that takes a function to evaluate if a condition is met, and a timeout in milliseconds. It returns a promise that resolves if the condition is met within the timeout, or rejects if the timeout is reached.
async function sleepUntil(f, timeoutMs) {
return new Promise((resolve, reject) => {
timeWas = new Date();
wait = setInterval(function() {
if (f()) {
console.log("resolved after", new Date() - timeWas, "ms");
clearInterval(wait);
resolve();
} else if (new Date() - timeWas > timeoutMs) { // Timeout
console.log("rejected after", new Date() - timeWas, "ms");
clearInterval(wait);
reject();
}
}, 20);
});
}
#javascript-tips #javascript #asynchronous