Skip to content

Instantly share code, notes, and snippets.

@P4
Created July 10, 2020 14:56
Show Gist options
  • Save P4/eeae0eadfd5e1de1288bb1d829e4e40a to your computer and use it in GitHub Desktop.
Save P4/eeae0eadfd5e1de1288bb1d829e4e40a to your computer and use it in GitHub Desktop.
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