Skip to content

Instantly share code, notes, and snippets.

@mattzeunert
Last active January 8, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattzeunert/c639ff38c2757cb610e8ce71e7525419 to your computer and use it in GitHub Desktop.
Save mattzeunert/c639ff38c2757cb610e8ce71e7525419 to your computer and use it in GitHub Desktop.
var waitFor = async function waitFor(conditionFn, { timeout = 15000, checkInterval = 25, debugString = null, } = {}) {
if (typeof conditionFn !== "function") {
throw Error("waitFor condition argument isn't a function. Did you mean waitForElement?");
}
if (!debugString) {
debugString = conditionFn.toString();
}
let startedAt = new Date();
let conditionResult = await conditionFn();
while (!conditionResult) {
await new Promise((resolve) => setTimeout(resolve, checkInterval));
if (new Date().valueOf() - startedAt.valueOf() > timeout) {
throw Error(`Wait for condition timed out after ${timeout} ms: ${debugString}`);
}
conditionResult = await conditionFn();
}
return conditionResult;
};
var waitForElement = function waitForElement(selector, { containingText = null, timeout = 15000, checkInterval = 25, } = {}) {
if (typeof selector !== "string") {
throw Error("waitForElement selector isn't a string: " + selector);
}
let debugString = `waitForElement "${selector}"`;
if (containingText) {
debugString += ` (containing text: "${containingText}")`;
}
return waitFor(() => {
const els = document.querySelectorAll(selector);
if (els.length > 0) {
if (containingText) {
let matchingEl = Array.from(els).find((el) => (el.textContent || "").includes(containingText));
if (matchingEl) {
return matchingEl;
}
}
else {
return els[0];
}
}
}, { timeout, checkInterval, debugString });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment