Web Development Tutorials




  
  

Window Timers

Two sets of windows methods relate to setting up timing devices to control the automatic display of pages. One set of methods introduces a delay before showing a page; the other set defines a continuous interval during which activities are repeated.

The Delay Timer

A delay timer is established with the setTimeout() method and cleared with the clearTimeout() method. The setTimeout() method causes the script to pause for a specified number of milliseconds. Its general format is shown below.


setTimeout("statement", milliseconds)

Figure 7-17. General format for delay timer.

A statement is a JavaScript statement, normally a function call, that is delayed, and milliseconds is the number of milliseconds to wait before the statement is executed.

One popular use of the timer is to delay transfer to a URL for a few seconds. The following link, for instance, transfers to the opening page of these tutorials in 5 seconds.

Tutorial Page
 

Figure 7-18. Using a delay timer.


window.onload = init;

function init()
{
var btnTransfer = document.getElementById("btnTransfer");
btnTransfer.onclick = Transfer;

}
function Transfer()
{
  document.getElementById("Message").innerHTML = 
    "(You will be transferred to the opening tutorial page in 5 seconds.)";
  setTimeout("location='../title.htm'", 5000);
}

<a href="#" id="btnTransfer">Tutorial Page</a>
<span id="Message"></span>

Listing 7-14. Code to establish a delay timer.

The script uses the [window].location property to transfer to the page after 5 seconds (5,000 milliseconds).

The setTimeout() method also can be used to produce a simple slide show wherein pages are displayed in sequence in a secondary window after timed delays. The following button runs a slide show of five images to demonstrate.


Figure 7-19. Running a slide show with a delay timer.

window.onload = init;

function init()

{
var SlideWindow;
var btnSlideShow = document.getElementById("btnSlideShow");
btnSlideShow.onclick = SlideShow;
}

function SlideShow()
{
  SlideWindow = open("Slide1.jpg", "", "width=300,height=200");
  SlideWindow.moveTo(400,400);
  setTimeout("SlideWindow.location='Slide2.jpg'", 2000);
  setTimeout("SlideWindow.location='Slide3.jpg'", 4000);
  setTimeout("SlideWindow.location='Slide4.jpg'", 6000);
  setTimeout("SlideWindow.location='Slide5.jpg'", 8000);
  setTimeout("SlideWindow.close()", 10000);
}

<input type="button" value="Slide Show" id="btnSlideShow">

Listing 7-15. Code to run a slide show with a delay timer.

A secondary window is opened and loaded with the image Slide1.jpg. Subsequent images are displayed in the same window at timed delays of 2 seconds. The second image is loaded after 2 seconds, the third image is loaded after 4 seconds, and so forth until the secondary window is closed after 10 seconds. Note that a window variable name, SlideWindow in this case, is required to be defined in the open() statement so that it can be referrred to when displaying the timed images. The script makes use of the window's location property to change the URL of the secondary window to the changing documents.

The setTimeout() method can be stopped at any time by issuing the clearTimeout() method. This method is not required unless the delay specified in the setTimeout() method needs to be aborted prior to its activation.

The Interval Timer

The setTimeout() method is most appropriate for a one-time delay in displaying a page, or it can be used to set different lengths of delays for multiple pages. The setInterval() delay method, though, can establish a fixed interval for repeated tasks.


variable = setInterval("statement", milliseconds)

Figure 7-20. General format for interval timer.

The variable is a variable name used to reference the timer, statement is a JavaScript statement to execute (usually a function call), and milliseconds is the interval of milliseconds between executions of the instruction. The difference in this timer is that the statement is executed repeatedly, every so many milliseconds, until the timer is turned off with the clearInterval() method.


clearInterval(variable)

Figure 7-21. General format to clear interval timer.

Here, variable is the name of the timer started in the associated setInterval() statement. Multiple timers can be active at the same time by assigning them to different variable names.

These methods are appropriate for executing an instruction every so many milliseconds. For example, the following buttons establish an interval timer for displaying a clock every second.

 


Figure 7-22. Using an interval timer.


window.onload = init;

function init()
{
var btnShowTimer = document.getElementById("btnShowTimer");
btnShowTimer.onclick = StartTimer;

var btnStopTimer = document.getElementById("bntStopTimer");
btnStopTimer.onclick=StopTimer;
}


function StartTimer()
{
  var Timer = setInterval("ShowClock()",1000);
}

function ShowClock()
{
  TheDate = new Date();
  document.getElementById("Clock").innerHTML = TheDate.toTimeString();
}

function StopTimer()
{
  clearInterval(Timer);
}

<input type="button" value="Show Clock" id="btnStartTimer">
<div style="font-family:impact; font-size:20pt">
  <span id="Clock"></span>
</div>
<input type="button" value="Stop Clock" id="btnStopTimer">

Listing 7-16. Code to use an interval timer.

The StartTimer() function is called to set up the interval timer to call the ShowClock() function once every second. The ShowClock() function, in turn, creates a Date object and extracts the time, displaying it in the output area. The Timer is turned off when the StopTimer() function is called.

The interval method can be used for a self-running slide show when the display of pages is for equal intervals of time. The following script reproduces the previous slide show by displaying an image every two seconds.



Figure 7-23. Running a slide show with an interval timer.


var slideCount;
var slideWindow;
var slideTimer ;

function init()
{
  var btnSlideShow = document.getElementById("bntSlideShow");
  bntSlideShow.onlick = slideShow1;
}


function slideShow1()
{
  slideCount = 1;
  slideWindow = open("Slide1.jpg", "", "width=300,height=200");
  slideWindow.moveTo(400,400);
  slideTimer = setInterval("showNextSlide()",2000);
}

function showNextSlide()
{
  slideCount ++;
  if (slideCount <= 5 && slideWindow.closed != true) {
    slideWindow.location = "Slide" + slideCount + ".jpg";
  }
  else {
    clearInterval(slideTimer);
    slideWindow.close();
 }
}

window.onload=init;

<input type="button" value="Show Slides" id="btnSlideShow">

Listing 7-17. Code to run a slide show with an interval timer.

Initially, a slide counter named SlideCount is established as a global variable to keep track of the sequence of slides. The image files are named Slide1.jpg, Slide2.jpg, and so forth, so the slide counter can be used to identify which slide to show by incrementing the counter from 1 to 5 and concatenating this variable to the text string "Slide" and appending ".jpg" to the end of the string to compose the image name.

When the SlideShow() function is called, the SlideCount is initialized, a secondary window is opened, and the first slide is loaded into the window. The window is assigned to a global variable for access by the multiple scripts that refer to it. Then an interval timer is established to call the ShowNextSlide() function once every two seconds.

The ShowNextSlide() function increments the SlideCount variable to point to the next slide. This counter value is used to compose the name of the next slide with the concatenation


"Slide" + slideCount + ".jpg"

This image is loaded into the window with the location property setting for the window. When the SlideCount variable has been incremented past 5, the timer is stopped and the window is closed since Slide5.jpg is the final slide in the sequence.

Checking for a Closed Window

A problem can occur when using an interval timer to control a secondary window. It arises when the user closes the secondary window. A JavaScript error is raised because the timer does not get cleared as it normally does when, for instance, a slide show comes to its normal end. As a result, the script continues to run but there is no secondary window into which the next page can be loaded.

A script needs to know whether the secondary window is still open before attempting to load a page or write to the window. This condition can be discovered with the window.closed property. This property value is true or false depending on the closed status of the window.

Returning to the previous script, this property test can be added as a second condition for continuing the slide show.


function showNextSlide()
{
  slideCount ++;
  if (slideCount <= 5 && slideWindow.closed != true) {
    slideWindow.location = "Slide" + slideCount + ".jpg";
  }
  else {
    clearInterval(SlideTimer);
    slideWindow.close();
  }
}

Listing 7-18. Script to check for a closed secondary window.

Here, the closed property of the named secondary window is checked. If the property is not true, then the window is open and its location property can be set with the next slide URL. Otherwise, if the secondary window is closed, the location property is not set and the timer is cleared.

Windows timers are very useful for automating scripts that perform HTML activities. There will be occasion to return to their use for more of these purposes in later tutorials.


TOP | NEXT: The screen Object