DEV Community

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

Posted on • Edited on

3 1

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay