admin管理员组

文章数量:1287584

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.

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.

Share Improve this question edited May 22, 2014 at 17:34 Larry Martell asked May 22, 2014 at 17:31 Larry MartellLarry Martell 3,7567 gold badges43 silver badges80 bronze badges 5
  • 2 Wherever your code is defining someObject, you should also accept a callback function, which you invoke after you define the variable. You probably should just pass the value directly to the callback, instead of sharing state with a global variable as well. – user229044 Commented May 22, 2014 at 17:34
  • Sounds like you're looking for promises. – Etheryte Commented May 22, 2014 at 17:34
  • @meagar: exactly. you should use a callback function – sjkm Commented May 22, 2014 at 17:35
  • 1 This is usually a symptom of bad code design. What are you actually trying to do? Why do you need to wait for this element to exist? Why doesn't it exist immediately? What is creating it? When it is being created? Why is it being created? What do you intend to do with it once it exists? – Kevin B Commented May 22, 2014 at 17:36
  • After my page is loaded I need to call a js function that will only exist some time after a table gets given a certain class. When I try to call that function from an onload function it fails most of the time because the table does not yet have the class. If I call that function from a setTimeout that waits 1 second it works 99% of the time. I'd like to just wait until the class gets put on the table and the function exists and then call it. – Larry Martell Commented May 22, 2014 at 17:41
Add a ment  | 

1 Answer 1

Reset to default 10

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);

本文标签: How to wait for an element to be defined in javascriptStack Overflow