CodingBison

The global window object provides several timer-related properties that allow us to set timers and when needed, to cancel them. Having timers is a powerful tool since that enables us to set certain actions to occur at precise time from now or to set certain actions to happen periodically in future.

These methods are setTimeout, clearTimeout, setInterval, and clearInterval. Here are their signatures:

 var retVal1 = setTimeout(callbackFunction, timeInMilliseconds, optionalArguments);
 clearTimeout(retVal1);

 var retVal2 = setInterval(callbackFunction, timeInMilliseconds, optionalArguments);
 clearInterval(retVal2);

The setTimeout() method takes the name of a callback function along with time (in milliseconds). When the specified time elapses, JavaScript invokes the specified callback function. setTimeout() also takes optional arguments and these arguments are passed to the callback function; note that passing optionalArguments may not work in Microsoft Internet Explorer. setTimeout() method returns a value that represents the timer. If we need to stop the timer from elapsing, then we can use clearTimeout() method and pass the returned value from the setTimeout() method.

Sometimes, we might need to do a task, over and over again. If we have to invoke these tasks using the setTimeout() method, then we would need to call setTimeout() again and again. For such use-cases, we can use JavaScript's setInterval() method -- once called this method invokes the callback function periodically after the specified timer elapses. Like setTimeout(), setInterval() also returns a value; if we choose to stop the setInterval timer, then we can call clearInterval() method and pass the returned value from the setInterval() step. Like setTimeout(), setInterval() also accepts a set of arguments.

Note that since window is the global object in a web browser and these methods are properties of the window object, we do not need to add window for callings its method. Thus, specifying setTimeout() is as good as specifying window.setTimeout()!

Next, we provide two simple examples to help us understand these timer methods.

The first example uses setTimeout() method to set a timer that elapses after 1 second (1000 milliseconds). Once the timer fires, it invokes the "feedTheDragon" callback function. This example keeps a count of the number of times the function is invoked and when the count reaches a value (in this case, 4), it cancels the timer using clearTimeout(). In fact, if we wanted, we could have simply skipped setting the timer when the total count reached 4! However, to demonstrate its usage, we did set the timer so that it could be canceled using a clearTimeout() call.

 <!doctype html>
 <html>
 <div id="div_id"> </div>
 <script type="text/javascript">

 //Global Variables
 var totalCount = 0;
 var elem = document.getElementById('div_id');

 // Feed the dragon.
 function feedTheDragon(whatToFeed) {
     elem.innerHTML += "<br>[" + (totalCount++) + "]"; 
     if (whatToFeed) {
         elem.innerHTML += "Time to feed " + whatToFeed +" to the dragon"; 
     } else {
         elem.innerHTML += "Time to feed the dragon"; 
     }   

     elem.innerHTML += "<br>Let us set the timeout again";
     var retVal = setTimeout(feedTheDragon, 1000, "Dragonberries");

     // If totalCount becomes 4 then stop feeding. 
     if (totalCount == 4) {
         elem.innerHTML += "<br><br>";
         elem.innerHTML += "That should be enough!! Let us cancel this timeout";
         clearTimeout(retVal);
     }
 }

 //Set timeout to feed the dragon; ignore the return value.
 setTimeout(feedTheDragon, 1000);

 </script>
 </html>

When we run the above program, we see the following messages getting printed on the browser, one after another (subsequent messages would be printed with a delay of 1 second). Since the first setTimeout() call does not pass the optional third parameter to the feedTheDragon() function, we see that the after the first timeout, the output is "Time to feed the dragon". Subsequent setTimeout() calls do pass the third parameter ("Dragonberries") to feedtheDragon() function and so we see the output text printing the same: "Time to feed Dragonberries to the dragon".

 [0]Time to feed the dragon
 Let us set the timeout again
 [1]Time to feed Dragonberries to the dragon
 Let us set the timeout again
 [2]Time to feed Dragonberries to the dragon
 Let us set the timeout again
 [3]Time to feed Dragonberries to the dragon
 Let us set the timeout again

 That should be enough!! Let us cancel this timeout

The second example uses setInterval() to perform the same task periodically and it modifies the earlier program to use setInterval() instead of setTimeout(). For this case, it is a must to call clearInterval(), if we wish to stop the periodic timer.

 <!doctype html>
 <html>
 <div id="div_id"> </div>
 <script type="text/javascript">

 //Global Variables
 var totalCount = 0;
 var elem = document.getElementById('div_id');

 // Feed the dragon.
 function feedTheDragon(whatToFeed) {
     elem.innerHTML += "<br>[" + (totalCount++) + "]"; 
     if (whatToFeed) {
         elem.innerHTML += "Time to feed " + whatToFeed +" to the dragon";
     } else {
         elem.innerHTML += "Time to feed the dragon"; 
     }   

     // If totalCount becomes 4 then stop feeding. 
     if (totalCount == 4) {
         elem.innerHTML += "<br><br>";
         elem.innerHTML += "That should be enough!! Let us cancel this interval";
         clearInterval(retVal);
     }
 }

 // Set a timer to feed the dragon. Store the return value. 
 var retVal = setInterval(feedTheDragon, 1000, "Dragonberries");

 </script>
 </html>

When we run this program, we would see the following messages getting printed on the browser, one after another:

 [0]Time to feed Dragonberries to the dragon
 [1]Time to feed Dragonberries to the dragon
 [2]Time to feed Dragonberries to the dragon
 [3]Time to feed Dragonberries to the dragon

 That should be enough!! Let us cancel this interval

As noted above, passing a parameter via setTimeout() and setInterval() method should work in most of the browsers except Microsoft Internet Explorer.

For Microsoft Internet Explorer, one way is to pass a parameter to the callback function is to use function closure; we can use closure to write a function that gets mapped to the local variable. Next, when timeout is called this function would automatically be bound to those parameters. Thus, we could simply rewrite the setTimeout call as: setTimeout((function() {feedTheDragon("Dragonberries")}), 1000); Now, the new (anonymous) function uses closure to associate the "Dragonberries" parameter with the feedTheDragon() function and when timeout happens, "DragonBerries" value would be passed automatically to feedTheDragon() function!





comments powered by Disqus