This is an example of the use of setTimeout() to detect if an element or object exists yet. In Javascript, timing is crucial. If an element hasn’t been loaded or rendered on the page yet, you can’t do something with it, so it is necessary to test for the existence of items that take a while to load.

This script was originally written to check if a lengthy array of objects had loaded yet.

var counter = 0; 
functionThatRequiresMyObject()
{
    var myObject = [something that may or may not be defined yet]

      //if myObject doesn't exist yet, and the counter is set at less than 10 times
      if((typeof myObject=="undefined")&&(counter<10))
     { 
           //increment the counter       
           counter++;
          //wait 1/2 second, then check for myObject again
          setTimeout("functionThatRequiresMyObject();",500);
     }
     else
     { 
          //do something with myObject 
     }
}

or, similarly:

var counter = 0; 
functionThatRequiresMyObject()
{
    //test for object is located elsewhere, perhaps in an init() function.
     if(myObjectIsLoaded ==true)
     {
          //do something with myObject
     }

     else{
   if(counter<10)
           {
              setTimeout("functionThatRequiresMyObject();",500  );   
   } 
  else  
          { 
   //do something with myObject
  }
  counter++
  }