[html5] Waiting for an object to be defined in javascript

Larry Martell larry.martell at gmail.com
Thu May 22 12:41:15 PDT 2014

On Thu, May 22, 2014 at 3:13 PM, Rik Sagar <org.whatwg at sagar.org> wrote:
> Depends where the object comes from is and who's setting it!
> Couldn't you fire an event when the object is created, then do whatever work
> you need to do in the event listener ?
> Alternatively, can "someObject" be an object inside "otherObject", for
> example, otherObject.someObject.
> If you have it that way, you can write a setter/getter on "otherObject" for
> someObject.  When someone does "otherObject.someObject = new Object();" your
> setter function gets called with the new value.
> Either is preferable to the busy loop approach if you can do it.

The scenario is: 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 function has not yet been defined.
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.

I think I may have this working. I did this:

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

    // the rest of the code
}, 10);

So far this looks good. I need to run it for a day or 2 and make sure.

> On Thu, May 22, 2014 at 10:32 AM, Larry Martell <larry.martell at gmail.com>
> wrote:
>> 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.

More information about the Help mailing list