Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for an element to be defined in javascript?

Tags:

javascript

I need to do the equivalent of this in javascript:

while (typeof someObject == 'undefined') {
     sleep(10);  // 10ms
}

And I just can't quite figure out how to code this.

I have this:

function sleep(ms, callback, arg) {
    setTimeout(function() {
        callback(arg);
    }, ms);
}

function waitForDef(elem) {
    if (typeof elem == 'undefined') {
        sleep(10, waitForDef, elem);
    }
}

But it's not clear to me how to use this from my code.

like image 939
Larry Martell Avatar asked Oct 22 '25 00:10

Larry Martell


1 Answers

Have an interval running that keeps checking on the element:

var interval = setInterval(function() {
    // get elem
    if (typeof elem == 'undefined') return;
    clearInterval(interval);

    // the rest of the code
}, 10);
like image 131
pavlindrom Avatar answered Oct 23 '25 15:10

pavlindrom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!