Skip to content

Instantly share code, notes, and snippets.

@jrc03c
Last active March 20, 2025 17:57
Show Gist options
  • Save jrc03c/21da877888d58185b32c86bdea8462c9 to your computer and use it in GitHub Desktop.
Save jrc03c/21da877888d58185b32c86bdea8462c9 to your computer and use it in GitHub Desktop.
querySelectorAsync
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