Created
July 10, 2020 14:56
-
-
Save P4/eeae0eadfd5e1de1288bb1d829e4e40a to your computer and use it in GitHub Desktop.
UserScript utilities
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
/** 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