Sometimes we need to wait for something to be happened before we execute a command or call a function or do something else.
By something I mean:
- rendering of a HTML element
- a JavaScript event
- response from API
and many other things.
Let's see how to write a couple of functions to tackle these scenarios:
Poling function 1: wait for HTML element
var waitForElement = function(elem) {
if (typeof elem == 'string') {
return new Promise(function (resolve) {
var wfelem = function () {
if (null != document.querySelector(elem)) {
resolve(document.querySelector(elem));
} else {
window.requestAnimationFrame(wfelem);
}
};
wfelem();
});
}
};
We can use the above poling function when we need to wait for a certain HTML element.
Example:
waitForElement('button#addToCart').then(function(button) {
button.textContent = 'Buy Now';
});
Poling function 2: wait until a function returns true
waitUntil = function(callback) {
if (typeof callback === 'function') {
return new Promise(function(resolve, reject) {
var tick = setInterval(function() {
if (callback() === true) {
clearInterval(tick);
return resolve();
}
});
});
} else {
console.error(callback + ' should be a function');
}
};
We can use the above function to wait until one or more conditions meet the criteria before further execution of the code.
Example:
window.waitUntil(function () {
return "complete" == document.readyState;
}).then(function () {
console.log("Page loading complete!");
});
Top comments (0)