Last active
August 22, 2022 03:27
-
-
Save nicanordlc/3c62223eb6f340601568c8b4dfe396e4 to your computer and use it in GitHub Desktop.
This function promises you to find an element on the page and return it back.
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
/** | |
* awaitFor | |
* | |
* given a selector this function promises to return a valid element when it finds it. | |
* you can manage the timeout and the step interval if needed. | |
* | |
* @param selector - the selector for the element you want | |
* @param options - configuration for the promise | |
* @param options.intervalStep - time between checking in seconds | |
* @param options.timeout - time in seconds to stop checking the element | |
* | |
* @returns {Promise} | |
*/ | |
export function awaitFor(selector, { | |
intervalStep = 1000, | |
timeout = 10, | |
all = false, | |
} = {}) { | |
const startTime = performance.now() | |
return new Promise((accept, reject) => { | |
const interval = setInterval(() => { | |
const element = all | |
? Array.from(document.querySelectorAll(selector)) | |
: document.querySelector(selector) | |
const timeElapsed = Math.trunc((performance.now() - startTime) / 1000) | |
console.log(`Searching for selector: '${selector}' (${timeElapsed}s)`); | |
if (all ? element.length : element) { | |
clearInterval(interval) | |
accept(element) | |
} else if (timeout > 0 && timeElapsed >= timeout) { | |
clearInterval(interval) | |
reject(`Element '${selector}' not found within ${ | |
timeElapsed | |
} second${timeElapsed > 1 ? 's' : ''}`) | |
} | |
}, intervalStep) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment