There are many different ways to solve this use case. You want to wait for an element to exist on the page and run a callback function when it does. It seems simple enough, but what’s the easiest way?
By using an async function and a while loop, we can wrap setTimeout in a promise, then await it, and then resolve the promise when the timeout completes. As you can see, it will continue the loop until we reach the timeout passed into the function (or the element is found).
async function waitForElement(selector, timeout = 15000) { const start = Date.now(); while (Date.now() - start < timeout) { const el = document.querySelector(selector); if (el) { return el; } await new Promise(resolve => setTimeout(resolve, 1000)); } return null; }
There are lots of other ways you can achieve this concept, from using setInterval
to using a MutationObserver
, but this approach is cleaner and easier to understand.
You could shorten the “if” to:
if (el || Date.now() – start > timeout)
If the “querySelector” can’t find the element it will return “null”, making the “if” and “else if” the same as it’ll call the callback with an “el” of “null”.