DEV Community

Cover image for 2 useful Polling functions in JavaScript
Shafiqul Islam Shuvo
Shafiqul Islam Shuvo

Posted on • Updated on

2 useful Polling functions in JavaScript

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();
        });
    }
};
Enter fullscreen mode Exit fullscreen mode

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';
});
Enter fullscreen mode Exit fullscreen mode

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');
    }
};
Enter fullscreen mode Exit fullscreen mode

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!");
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)