Last active
March 20, 2025 17:57
-
-
Save jrc03c/21da877888d58185b32c86bdea8462c9 to your computer and use it in GitHub Desktop.
querySelectorAsync
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
function querySelectorAsync(selector, ttl, root) { | |
return new Promise((resolve, reject) => { | |
let interval, timeout | |
ttl = ttl || 10000 | |
root = root || document | |
try { | |
timeout = setTimeout(() => { | |
clearInterval(interval) | |
throw new Error(`Unable to find element with selector "${selector}"!`) | |
}, ttl) | |
interval = setInterval(() => { | |
const el = root.querySelector(selector) | |
if (!el) { | |
return | |
} | |
clearTimeout(timeout) | |
clearInterval(interval) | |
return resolve(el) | |
}, 10) | |
} catch (e) { | |
clearTimeout(timeout) | |
clearInterval(interval) | |
return reject(e) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment