Last active
September 30, 2019 12:44
-
-
Save funkyremi/db42f9358c10675f31ef6b2841d5da00 to your computer and use it in GitHub Desktop.
Function that wait for an element to exist in DOM then return it.
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
export function getDomElement(selector = '', timeoutMs = 1000, pollIntervalMs = 10) { | |
const timeStart = performance.now(); | |
return new Promise((resolve, reject) => { | |
const intervalId = setInterval(() => { | |
const timeNow = performance.now(); | |
const element = document.querySelector(selector); | |
if (element) { | |
clearInterval(intervalId); | |
resolve(element); | |
} else if ((timeNow - timeStart) > timeoutMs) { | |
clearInterval(intervalId); | |
reject(new Error('Timeout')); | |
} | |
}, pollIntervalMs); | |
}); | |
} | |
export function getDomElements(selector = '', timeoutMs = 1000, pollIntervalMs = 10) { | |
const timeStart = performance.now(); | |
return new Promise((resolve, reject) => { | |
const intervalId = setInterval(() => { | |
const timeNow = performance.now(); | |
const elements = document.querySelectorAll(selector); | |
if (elements) { | |
clearInterval(intervalId); | |
resolve(elements); | |
} else if ((timeNow - timeStart) > timeoutMs) { | |
clearInterval(intervalId); | |
reject(new Error('Timeout')); | |
} | |
}, pollIntervalMs); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment