Skip to content

Instantly share code, notes, and snippets.

@funkyremi
Last active September 30, 2019 12:44
Show Gist options
  • Save funkyremi/db42f9358c10675f31ef6b2841d5da00 to your computer and use it in GitHub Desktop.
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.
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