Javascript: use setTimeout() for detecting whether an object or element exists yet
October 23, 2012
Javascript | Web Building
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++
  }


Ads by Google

Posted by ellen at October 23, 2012 11:58 AM


Ads by Google

 RSS   |   Contact Me

Ads by Google

Ads by Google