Reena Verma
Reena Verma

Reputation: 1685

Wait for element without using promises (ES5)

What is the best way to:

I must use ES5, which rules out promises and async.

Here's an example I'm trying to work on below, which consoles.log true in valueCallBack, but doesn't return true (found variable).

function waitForElement(elementId, callBack){
    var found;
    window.setTimeout(function(){
        var element = document.querySelector(elementId);

        found = true;
        valueCallBack(found)

        if(element) {
            callBack(elementId);
        } else {
            waitForElement(elementId, callBack);
        }
    }, 1000);
}

function valueCallBack(found){
    // console.log("this console logs true", found);
    return found;
};


waitForElement('.select-fare-type-modal:not(.ng-hide)',function(){
    // ELEMENT FOUND AND DO SOMETHING
})

Upvotes: 0

Views: 382

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20451

Your code is setting multiple timers. If you want your function to run after certain intervals, you can try with a simple setInterval. Once your element is found (exists), you can clear the same interval using its ID.

let clearId = null;
function waitForElement(elementId, callBack){
    var found = false;
    clearId  = window.setInterval(function(){
        var element = document.querySelector(elementId);
  if(element){
   callBack();
}
    }, 1000);
}

let alertTrue = () => {
alert(true);
clearInterval(clearId);
}

waitForElement('#yourElementId',alertTrue );

Upvotes: 1

Related Questions