Team LiB
Previous Section Next Section

JavaScript Timers

One very powerful aspect of JavaScript is the ability to set a delay before performing an action. For example, if a user is taking an online quiz that requires him to finish within a given amount of time, you can use a JavaScript timer to warn him when he was nearing the end of his allotted time.

The following very simple example demonstrates the use of two independent timers:

<html>
  <head>
    <title>
        JavaScript Professional Projects - Timers
    </title>

    <script language="JavaScript">
    <!--
       var timeout1, timeout2;

       function onLoad()
       {
         var command = "alert( 'You have only 10 seconds left!' );";
         timeout1 = window.setTimeout( command, 20000 );
         timeout2 = window.setTimeout( "timesUp();", 30000 );
       }

       function timesUp()
       {
         alert( "Time is up!" );
         document.theForm.theButton.disabled = true;
       }

       function checkAnswer()
       {
         window.clearTimeout( timeout1 );
         window.clearTimeout( timeout2 );
 
         if( document.theForm.theAnswer.value == "3x2+10x" )
         {

           alert( "That is correct!" );
         }
         else
           alert( "Sorry, the correct answer is: 3x2+10x" );
         }
       }
     // -->
     </script>

  </head>
 
  <body onLoad="JavaScript: onLoad();">

     <center>
       <font size=6>JavaScript Professional Projects</font><br>
       <font size=4>Chapter 8: Timers</font>
     </center>

     <br><br>
     <br>
     You have 30 seconds to answer the following question: <br>
     <br>

     <form name="theForm" onSubmit="JavaScript: checkAnswer();">
       What is the differential of the following function:&nbsp;
       <font face="Courier">x<sup>3</sup>+5x<sup>2</sup>+</font>9 ?
       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       <input type="text" name="theAnswer" size="20"><br>
       <br>
       <input type="submit" value="Submit" name="theButton">
     </form>

  </body>
</html>

The first timer,

var command = "alert( 'You have only 10 seconds left!' );";
timeout1 = window.setTimeout( command, 20000 );

is set to go off 20 seconds (20,000 milliseconds) after the page loads. This warns the user via an alert dialog that he has only 10 more seconds to complete the quiz.

Ten seconds after the first alert dialog is closed, the second timer,

timeout2 = window.setTimeout( "timesUp();", 30000 );

goes off and disables the Submit button on the form. The first timer runs a single line of JavaScript, which is given as a parameter. The second timer calls a function; this is called a function callback. Both calls to the window object's method, setTimer(), return a handle to the timeout object, which can be used to cancel the timeout prematurely. If the user submits an answer before the timers have run their course, the separate calls to window.clearTimeout(),

window.clearTimeout( timeout1 );
window.clearTimeout( timeout2 );

will cancel the timers. If these two method calls were not included, the user would still get the timeout messages after submitting the form.

It is important to note that all timers in Internet Explorer are paused when the first alert dialog is popped up. If the user decided not to close this dialog, he would have as long as he needed (plus ten seconds) to complete the quiz. Most users will not know this—especially if no running clock is visible—but it still must be taken into consideration.

Sometimes it is useful to display an onscreen clock, so that the user knows exactly how much time has passed. Doing so is very simple with JavaScript timers:

<html>
  <head>
    <title>
        JavaScript Professional Projects - Timers
    </title>

    <script language="JavaScript">
    <!--
      var timeout, currentTime = 30;
      function adjustTime()
      {
        window.defaultStatus = "Time left = 0:" + 
          ( currentTime < 10 ? "0" : "" ) + currentTime;

          if( currentTime == 10 )
          {
             alert( "You have only 10 seconds left!" );
          }
          else if( currentTime == 0 )
          {
             alert( "Time is up!" );
             document.theForm.theButton.disabled = true;
             return;
          }

          currentTime = currentTime - 1;
          timeout = window.setTimeout( "adjustTime();", 1000 );
          }

          function checkAnswer()
          {
            if( !document.theForm.theButton.disabled )
          {
              window.clearTimeout( timeout );
 
              if( document.theForm.theAnswer.value == "3x2+10x" )
              {
                 alert( "That is correct!" );
              }
              else
              {
                 alert( "Sorry, the correct answer is: 3x2+10x" );
              }
          }
       }
     // -->
     </script>
 
  </head>
<body onLoad="JavaScript: adjustTime();">

  <center>
    <font size=6>JavaScript Professional Projects</font><br>
    <font size=4>Chapter 8: Timers</font>
  </center>

  <br><br>
  <br>
  You have 30 seconds to answer the following question: <br>
  <br>

  <form name="theForm" onSubmit="JavaScript: checkAnswer();">
    What is the differential of the following function:&nbsp;
    <font face="Courier">x<sup>3</sup>+5x<sup>2</sup>+</font>9 ?
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="text" name="theAnswer" size="20"><br>
    <br>
    <input type="submit" value="Submit" name="theButton">
  </form>
 </body>
</html>

This example performs the same function as the previous example, but it displays a timer in the window's status bar that counts down the amount of time left to answer the question.

It might also be handy to show the current time onscreen, so that the user of a Web application can know the correct time. This would be useful when time-sensitive activities are being performed.

Here's how to display the local machine's clock time in the browser:

<html>
  <head>
    <title>
        JavaScript Professional Projects - Timers and Time
    </title>

    <script language="JavaScript">
    <!--
      function displayTime()

      { 
        var now = new Date();
        var h = now.getHours();
        var m = now.getMinutes();
        var s = now.getSeconds(); 

        with( document.theForm )
        {
          hours.value = h % 12;
          minutes.value = ( m < 10 ? "0" : "" ) + m;
          seconds.value = ( s < 10 ? "0" : "" ) + s;
          range.value = ( h >= 12 ? "PM" : "AM" );
        }

        window.setTimeout( "displayTime();", 1000 );
      }
    // -->
    </script>

    </head>
  
    <body onLoad="JavaScript: displayTime();">

      <center>
        <font size=6>JavaScript Professional Projects</font><br>
        <font size=4>Chapter 8: Timers and Time</font>
      </center>
      
      <br><br>
      <br><br>

      <form name="theForm">
        <table>
          <tr>
            <td><input name="hours" size="2"></div>
            </td> <td><b><font size="5">:</font></b></td>
            <td><input name="minutes" size="2"></div></td>
            <td><b><font size="5">:</font></b></td>

            <td><input name="seconds" size="2"></div></td>
            <td><input name="range" size="2"></div></td>
          </tr>
        </table>
      </form>
  </body>
</html>

You can, of course, query a server for the time and display that in the browser instead.

Creating a One-Shot Timer

The quiz example above used a timer that executed only once. Such a timer is called a one-shot timer. To create a one-shot timer, you can use the following syntax:

window.setTimeout( "<statement>", millisecondDelay );

This method call will cause the statement or statements as the first parameter (they must be enclosed in quotation marks) to execute after the specified delay.

Creating a Multi-Shot Timer

Creating a multi-shot timer is just as easy as creating a one-shot timer. The only difference is that one of the statements that are passed as the first parameter needs to contain either another setTimeout() call or a call to a function that makes a setTimeout() call. In the example above, the following function:

function displayTime()
{
  var now = new Date();
  var h = now.getHours();
  var m = now.getMinutes();
  var s = now.getSeconds();

  with( document.theForm )
  {
    hours.value = h % 12;
    minutes.value = ( m < 10 ? "0" : "" ) + m;
    seconds.value = ( s < 10 ? "0" : "" ) + s;
    range.value = ( h >= 12 ? "PM" : "AM" );
  }
    window.setTimeout( "displayTime();", 1000 );
  }

is called when the page loads and contains the statement

window.setTimeout( "displayTime();", 1000 );

which creates a callback to the same function. This process will loop the entire time the page is being displayed.


Team LiB
Previous Section Next Section