Skip to content

Instantly share code, notes, and snippets.

@manavortex
Last active March 13, 2021 10:58
Show Gist options
  • Save manavortex/5b994a2008eef08224cb4a2b849cc73b to your computer and use it in GitHub Desktop.
Save manavortex/5b994a2008eef08224cb4a2b849cc73b to your computer and use it in GitHub Desktop.
async function waitForElement
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