HTML and CSS Reference
In-Depth Information
Running Timed Commands
You've completed the functions required for the countdown clock, but the clock is
largely static, changing only when the page is reloaded by the browser. Hector wants
the clock to be updated constantly so that it always shows the current time and the time
remaining until the New Year's Bash. To do this, you need to rerun the clock function at
specified times. JavaScript provides two methods for doing this: time-delayed commands
and timed-interval commands.
Working with Time-Delayed Commands
A time-delayed command is a JavaScript command that is run after a specified amount of
time has passed. The syntax to run a time-delayed command is
setTimeout(“ command ”, delay );
where command is a JavaScript command and delay is the delay time in milliseconds
before a browser runs the command. The command must be placed within either double
or single quotation marks. For example, the following command sets a 5-millisecond
delay before a browser runs the showClock() function:
setTimeout(“showClock()”, 5);
In some JavaScript programs, you may want to cancel a time-delayed command. This
can be necessary in programs where other user actions remove the need to run a time-
delayed command. To cancel the command, you run the command
and JavaScript cancels the currently scheduled time-delayed command before it is run by
the browser.
There is no limit to the number of time-delayed commands a browser can process. To
distinguish one time-delayed command from another, you can assign a unique identi-
fication to each command. You store the ID value of each time-delayed command as a
variable as follows
timeID = setTimeout(“ command ”, delay );
where timeID is a variable that stores the ID of the command. After you've assigned an
ID to a time-delayed command, you can cancel it using the method
clearTimeout( timeID );
where once again timeID is the variable that stores the ID of the command.
Running Commands at Specified Intervals
The other way to time JavaScript commands is by using a timed-interval command ,
which instructs browsers to run the same command repeatedly at specified intervals. The
method to run such a command is
setInterval(“ command ”, interval );
where command is the JavaScript command that is to be run repeatedly and interval is
the interval in milliseconds before the command is run again. To instruct browsers to stop
running the command, you use the following method:
As with time-delayed commands, you may have several timed-interval commands run-
ning simultaneously. To distinguish one timed-interval command from another, you store
the time ID in a variable using the setInterval() method as follows
timeID = setInterval(“ command ”, interval );
Search WWH ::

Custom Search