Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UserScript utilities
/** returns a promise that resolves when element becomes available */
function waitForElement(selector, timeout=1000) {
return new Promise((resolve, reject) => {
let start, element;
requestAnimationFrame(function wait(timestamp) {
if (start == null) start = timestamp;
element = document.querySelector(selector);
if (element) {
resolve(element);
} else {
const elapsed = timestamp - start;
if (elapsed < timeout) {
requestAnimationFrame(wait)
} else {
reject(`timed out after ${elapsed}ms`)
}
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment