Last active
March 13, 2021 10:58
-
-
Save manavortex/5b994a2008eef08224cb4a2b849cc73b to your computer and use it in GitHub Desktop.
async function waitForElement
This file contains hidden or 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
let timeout = 75; | |
const maxTimeout = 5000; | |
/** | |
* Async function: call with checkElement('#myElement').then((el) { ... }) . | |
* Or see first block in waitForAndPrepend as per nightpool's suggestion in MR 2037 | |
* | |
* @param {string} selector - document query selector. | |
* @param {string} returnAry - run querySelectorAll rather than querySelector? | |
*/ | |
async function waitForElement(selector, returnAry = false) { | |
while (document.querySelectorAll(selector).length === 0) { | |
timeout = Math.max(timeout*2, maxTimeout); | |
await new Promise((resolve) => setTimeout(resolve, timeout)); | |
} | |
return returnAry ? document.querySelectorAll(selector) : document.querySelector(selector); | |
} | |
window.waitForElement = waitForElement |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment