As Time Goes By


JavaScript provides several functions that allow you to execute code as time passes, either periodically or after a specified interval. These functions are technically methods of the Global JavaScript object, which is the same thing as the window object for JavaScript code executing against a document loaded in a browser. As usual, you don’t need to reference the Window (or Global) object to use the methods because it’s implied.

Table 8-4 shows the JavaScript time-related methods.

Table 8-4: Time-Related Methods

Method

Purpose

clearInterval

Stops the timer started using the setInterval method

setInterval

Executes specified code periodically, using the interval specified (this can be thought of as starting a timer)

setTimeout

Executes specified code following an interval

These time-related methods are important in a chapter about events because essentially what you’re doing when you start a timer is registering an event that’s handled either periodically or after an interval (depending on whether you’ve used setInterval or setTimeout).

Advanced Note

Most modern programming languages provide some facility analogous to the JavaScript time-related methods. For example, in Visual Basic and C# .NET, the functionality of a timer is provided by the Timer component.

Note

As an exercise, why not implement the functionality of the setInterval method using a loop and the setTimeout method? (It’s convenient to have both methods, but you don’t really need them.)

Let’s work through a simple example that uses the setInterval method. In our example, the user enters a name for an object and clicks the Start button. The program then displays the object name and the current time, updated every second, in a <textarea> box (see Figure 8-11). The user also has the ability to stop the timer by clicking the Stop button shown in Figure 8-11.

click to expand
Figure 8-11: The setInterval method is used to display the time at one-second intervals.

Here’s the HTML form used to provide the user interface for this application (the table tags used for formatting are omitted for clarity):

 <FORM name="theForm">  Name your object: <input type=text name="txtName"> <input type=button value="Start!"     onClick="startIt (txtName.value);"> <input type=button value="Stop!"     onClick="stopIt();"> <textarea name="txtFired" cols = 60 rows=20> </textarea> </FORM> 

Note that when the Start button is clicked, a function named startIt is executed. When the Stop button is clicked, the stopIt function is executed.

The program code starts by declaring two variables that will be accessible to all functions in the program, one for referencing the object that is to be created, the other for storing the timer identification (which will be needed to stop the timer):

 var timerID;  var x; 

Here is the constructor for the Thing object:

 function Thing (name) {     this.name = name;  } 

Turning to the startIt function, what it does is to instantiate a Thing object using the name entered by the user. Next (and last) comes a call to the setInterval method:

 function startIt (name) {     x = new Thing (name);     timerID = setInterval("fireIt()", 1000);  } 

The setInterval method tells the computer to execute the code contained in the function fireIt once every 1,000 milliseconds. (As you likely know, 1,000 milliseconds is 1 second.) The return value of the setInterval method identifies the timer so that it can be stopped. It’s easy to imagine an application that sets many timers, hence the need for a way to identify individual timers.

Here’s the fireIt method, which creates a Date object containing the current date and time, and displays it, along with the Thing object name, each time the timer is fired:

 function fireIt () {     var now = new Date();     var displayStr = window.document.theForm.txtFired.value;     displayStr += "Hello: " + x.name +  " " + now + "\r\n";     window.document.theForm.txtFired.value = displayStr;  } 

All that remains is to provide the ability to stop the timer, which is accomplished in the stopIt function using the clearInterval method and the timer’s identification:

 function stopIt() {     clearInterval(timerID);  } 

Listing 8-6 shows the complete code for the program. If you’ve got the time, load it up in a browser, and go ahead and watch it fire. When the time is the last time, you can stop the process by clicking the Stop button.

Listing 8.6: Using a Timer

start example
 <HTML> <HEAD> <TITLE>As time goes by...</TITLE> <SCRIPT>  var timerID;  var x;  function Thing (name) {     this.name = name;  }  function fireIt () {     var now = new Date();     var displayStr = window.document.theForm.txtFired.value;     displayStr += "Hello: " + x.name + " "  + now + "\r\n";     window.document.theForm.txtFired.value = displayStr;  }  function startIt (name) {     x = new Thing (name);     timerID = setInterval("fireIt()", 1000);  }  function stopIt() {     clearInterval(timerID);  }  </SCRIPT> </HEAD> <BODY> <TABLE> <FORM name="theForm"> <TR> <TD>Name your object:</TD> <TD> <input type=text  name="txtName"> </TD> </TR> <TR> <TD> </TD> <TD> <input type=button value="Start!"     onClick="startIt (txtName.value);"> </TD> <TD> <input type=button value="Stop!"     onClick="stopIt();"> </TD> </TR> <TR> <TD> </TD> <TD> </TD> </TR> <TR> <TD colspan=2> <textarea name="txtFired" cols = 60  rows=20> </textarea> </TD> </TR> </FORM> </TABLE> </BODY> </HTML> 
end example

I know that printing out the current time every second doesn’t seem like a big deal. But bear in mind that all kinds of functionality (think animations, simulations, and automatic updating) can be accomplished using a timer.




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net