Skip to content

Instantly share code, notes, and snippets.

@a904guy
Created December 10, 2025 09:25
Show Gist options
  • Select an option

  • Save a904guy/504199ed9e16a92696d80378f9f85da1 to your computer and use it in GitHub Desktop.

Select an option

Save a904guy/504199ed9e16a92696d80378f9f85da1 to your computer and use it in GitHub Desktop.
Wait for Element Javascript Functions
const DEFAULT_INTERVAL_MS = 500;
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
/**
* Base polling helper.
* Returns the interval ID so callers can cancel with clearInterval if needed.
*/
function pollUntil(fn, {
interval = DEFAULT_INTERVAL_MS,
timeout = DEFAULT_TIMEOUT_MS,
onTimeout = null
} = {}) {
let elapsed = 0;
const id = setInterval(() => {
const done = fn();
if (done) {
clearInterval(id);
return;
}
if (timeout !== Infinity) {
elapsed += interval;
if (elapsed >= timeout) {
clearInterval(id);
if (typeof onTimeout === 'function') {
onTimeout();
}
}
}
}, interval);
return id;
}
/**
* Wait indefinitely for an element to appear, then invoke callback(element).
*/
function waitForeverForElement(selector, callback, parent = document) {
return pollUntil(
() => {
const element = parent.querySelector(selector);
if (element) {
if (typeof callback === 'function') {
callback(element);
}
return true;
}
return false;
},
{
interval: DEFAULT_INTERVAL_MS,
timeout: Infinity
}
);
}
/**
* Wait (with timeout) for an element to appear, then invoke callback(element).
*/
function waitForElement(selector, callback, parent = document, {
interval = DEFAULT_INTERVAL_MS,
timeout = DEFAULT_TIMEOUT_MS
} = {}) {
return pollUntil(
() => {
const element = parent.querySelector(selector);
if (element) {
if (typeof callback === 'function') {
callback(element);
}
return true;
}
return false;
},
{
interval,
timeout,
onTimeout: () => {
console.error(
`Failed to find element "${selector}" after ${timeout / 1000} seconds.`
);
}
}
);
}
/**
* Wait (with timeout) for an element to be removed, then invoke callback(null).
*/
function waitForElementRemoval(selector, callback, parent = document, {
interval = DEFAULT_INTERVAL_MS,
timeout = DEFAULT_TIMEOUT_MS
} = {}) {
return pollUntil(
() => {
const element = parent.querySelector(selector);
if (!element) {
if (typeof callback === 'function') {
callback(null);
}
return true;
}
return false;
},
{
interval,
timeout,
onTimeout: () => {
console.error(
`Element "${selector}" still present after ${timeout / 1000} seconds.`
);
}
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment