JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Timers in a Web Page

We can create two types of timers in IE 4.0+ and NN 4.0+ browsers. The one-shot timer triggers just once after a certain period of time, and the second type of timer continually triggers at set intervals. We will investigate each of these types of timers in the next two sections. Note that the first type, the one-shot timer, is the only one available in older browsers supporting JavaScript.

Within reasonable limits we can have as many timers as we want and can set them going at any point in our code, such as at the window onload event or at the click of a button. Common uses for timers include advertisement banner pictures that change at regular intervals or display the changing time in a web page. Also all sorts of animation done with DHTML need setTimeout() or setInterval()—we'll be looking at DHTML later on in the book.

One-Shot Timer

Setting a one-shot timer is very easy: we just use the window object's setTimeout() method.

window.setTimeout("your JavaScript code", milliseconds_delay)

The method setTimeout() takes two parameters. The first is the JavaScript code we want executed, and the second is the delay, in milliseconds (thousandths of a second), until the code is executed.

The method returns a value (an integer), which is the timer's unique ID. If we decide later that we want to stop the timer firing, we use this ID to tell JavaScript which timer we are referring to.

For example, to set a timer that will fire 3 seconds after the page has loaded, we could use the following code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language=JavaScript type="text/javascript">
var timerID;
function window_onload()
{
   timerID = setTimeout("alert('Times Up!')",3000);
   alert("Timer Set");
}
</script>
</head>
<body language = JavaScript onload="window_onload()">
</body>
</html>

Save this file as timertest.htm, and load it into your browser. In this page a message box will appear 3,000 milliseconds (that is 3 seconds) after the onload event of the window has fired.

Although setTimeout() is a method of the window object, you'll remember that because the window object is at the top of the hierarchy, we don't need to use its name when referring to its properties and methods. Hence, we can use setTimeout() instead of window.setTimeout().

It's important to note that setting a timer does not stop script from continuing to execute. The timer runs in the background and fires when its time is up. In the meantime the page runs as normal, and any script after we start the timer's countdown will run immediately. So, in this example, the alert box telling us that the timer has been set appears immediately after the code setting the timer has been executed.

How about if we decided that we wanted to stop the timer before it fired?

To clear a timer we use the window object's clearTimeout() method. This takes just one parameter, the unique timer ID that the setTimeout() method returns.

Let's alter the preceding example and provide a button that we can click to stop the timer.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language=JavaScript type="text/javascript">
var timerID;
function window_onload()
{
   timerID = setTimeout("alert('Times Up!')",3000);
   alert("Timer Set");
}
function butStopTimer_onclick()
{
   clearTimeout(timerID);
   alert("Timer has been cleared");
}
</script>
</head>
<body language=JavaScript onload="window_onload()">
<form name=form1>
<input type="button" value="Stop Timer" name=butStopTimer language=JavaScript

   onclick="return butStopTimer_onclick()">
</form>
</body>
</html>

Save this as timertest2.htm, and load it into your browser. Now if we click the Stop Timer button before the three seconds are up, the timer will be cleared. This is because the button is connected to the butStopTimer_onclick() function, which uses the timer's ID timerID with the clearTimeout() method of the window object.

Try It Out – Updating a Banner Advertisement

We'll now look at a bigger example using the setTimeout() method. The following example creates a web page with an image banner advertisement, which changes every few seconds.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language=JavaScript type="text/javascript">
var currentImgNumber = 1;
var numberOfImages = 3;
function window_onload()
{
   setTimeout("switchImage()",3000);
}
function switchImage()
{
   currentImgNumber++;
   document.imgAdvert.src = "AdvertImage" + currentImgNumber + ".jpg";
   if (currentImgNumber < numberOfImages)
   {
      setTimeout("switchImage()",3000);
   }
   }
</script>
</head>
<body onload="window_onload()">
<img src="AdvertImage1.jpg" name="imgAdvert">
</body>
</html>

Once you've typed in the code, save the page as Adverts.htm. You'll also need to create three images named AdvertImage1.jpg, AdvertImage2.jpg, and AdvertImage3.jpg (alternatively, the three images are supplied with the downloadable code for the book).

When the page is loaded, we start with a view of AdvertImage1.jpg, as shown in Figure 9-5.

Click To expand
Figure 9-5

In three seconds this changes to the second image, as shown in Figure 9-6.

Click To expand
Figure 9-6

Finally, three seconds later, a third and final image loads, as shown in Figure 9-7.

Click To expand
Figure 9-7

How It Works

When the page loads, the <img> tag has its src attribute set to the first image.

<img src="AdvertImage1.jpg" name="imgAdvert">

Within the <body> tag, we connect the window object's onload event handler to the function window_onload().

function window_onload()
{
   setTimeout("switchImage()",3000)
}

In this function we use the setTimeout() method to start a timer running that will call the function switchImage() in three seconds. Since we don't have to clear the timer, we haven't bothered to save the timer ID returned by the setTimeout() method.

The switchImage() function changes the value of the src property of the img object corresponding to the <img> tag in our page.

function switchImage()
{
   currentImgNumber++;
   document.imgAdvert.src = "AdvertImage" + currentImgNumber + ".jpg";

Our advertisement images are numbered 1 to 3: AdvertImage1.jpg, AdvertImage2.jpg, and AdvertImage3.jpg. We keep track of the number of the advertisement image that is currently loaded in the page in the global variable currentImgNumber, which we defined at the top of the script block and initialized to 1. To get the next image we simply increment that variable by 1, and then update the image loaded by setting the src property of the img object, using the variable currentImgNumber to build up its full name.

   if (currentImgNumber < numberOfImages)
   {
      setTimeout("switchImage()",3000);
   }
}

We have three advertisement images we want to show. In the if statement we check to see whether currentImgNumber, which is the number of the current image, is less than three. If it is, it means there are more images to show, and so we set another timer going, identical to the one we set in the window object's onload event handler. This timer will call this function again in three seconds.

Prior to version 4 browsers, this was the only method of creating a timer that fired continually at regular intervals. However in version 4 and later browsers, we'll see next that there's an easier way.

Setting a Timer that Fires at Regular Intervals

The introduction of IE and NN version 4 browsers saw new methods added to the window object for setting timers, namely the setInterval() and clearInterval() methods. These work in a very similar way to setTimeout() and clearTimeout(), except that the timer fires continually at regular intervals rather than just once.

The method setInterval() takes the same parameters as setTimeout(), except that the second parameter now specifies the interval, in milliseconds, between each firing of the timer, rather than just the length of time before the timer fires.

For example, to set a timer that will fire the function myFunction() every 5 seconds, the code would be as follows:

var myTimerID = setInterval("myFunction()",5000);

As with setTimeout(), the setInterval() method returns a unique timer ID that you'll need if you want to clear the timer with clearInterval(), which works identically to clearTimeout(). So to stop the timer started above, we would use the following:

clearInterval(myTimerID);

Try It Out – World Time Converter (Part 2)

Let's change the world time example that we saw earlier, so that it displays local time and selected city time as a continuously updating clock.

We'll be making changes to the WorldTimeConverter.htm file, so open that in your text editor. Add the following function before the functions that are already defined:

var daylightSavingAdjust = 0;
function window_onload()
{
   updateTimeZone();
   window.setInterval("updateTime()",1000);
}
function updateTimeZone()
{

Next edit the <body> tag so it looks like this:

<body language=JavaScript onload="return window_onload()">

Resave the file, and then load WorldTimeConverterFrameset.htm into your browser. (Remember that an NN 4.06+ or an IE 4.0+ browser is needed.) The page should look the same as the previous version of the time converter, except that the times are continually updated every second.

How It Works

The changes were short and simple. In the function window_onload(), we have added a timer that will call the updateTime() function every 1,000 milliseconds, that is, every second. It'll keep doing this until we leave the page. Previously our updateTime() function was only called when the user clicked either the list box and selected a different city or the summer time checkbox.

The window_onload() function is connected to the window object's onload event in the <body> tag, so once the page has loaded our clock starts running.

Try It Out – Scrolling Status Bar Text

Let's look at a second example using the setInterval() method. This time it's a scrolling status bar text, which you will find on many websites.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language = JavaScript type="text/javascript">
var message = "Beginning JavaScript from Wrox Press";
var startChar = 0;
var maxLength;
function window_onload()
{
   var availWidth = 0;
   var spaces = "";
   if (navigator.appName == "Netscape")
   {
      availWidth = window.innerWidth / 10;
   }
   else
   {
      availWidth = document.body.scrollWidth / 10;
   }
   while (availWidth > 0)
   {
      spaces = spaces + " ";
      availWidth--;
   }
   message = spaces + message;
   maxLength = message.length - 1;
   setInterval("scrollMessage()",65);
}
function scrollMessage()
{
   window.status = message.substring(startChar);
   startChar++;
   if (startChar == maxLength)
    
   {
      startChar = 0;
   }
}
</script>
</head>
<body language=JavaScript onload="return window_onload()">
<p>Scrolling Status Bar Example</p>
</body>
</html>

Save the page as scrolling_status.htm and load it into your browser. In the status bar at the bottom of the browser's window, you'll see this scrolling message: Beginning JavaScript from Wrox Press.

How It Works

At the top of the script block we define three global variables, as follows:

var message = "Beginning JavaScript from Wrox Press";
var startChar = 0;
var maxLength;

The message we want scrolled in the status bar is stored in the variable message. The variable startChar will later be used to determine the portion of the message to be displayed in the scroll bar and will help give the impression of text scrolling from the right and disappearing off to the left. The variable maxLength will later store the length of the string to be displayed.

When the message first appears in the status bar, we want it to appear approximately in the middle as shown in Figure 9-8.

Click To expand
Figure 9-8

To achieve this, we need to pad the front of the message with enough spaces so that it will be approximately in the middle. Otherwise, the message will start being displayed at the left of the status bar. The question is how many spaces do we need? This will depend to some extent on the user's screen resolution and how wide his browser window is. We deal with this in the window_onload() function that is connected to the window object's onload event in the <body> tag for the page. We find out how many pixels wide the browser window is and then divide that by ten to give us a very rough guide to the number of spaces required.

Finding out the width of a window requires the use of different properties for Netscape Navigator and Internet Explorer browsers. With Netscape 4.0+, window.innerWidth gives us the inner width of the window in pixels.

function window_onload()
{
   var availWidth = 0;
   var spaces = "";
   if (typeof window.innerWidth != 'undefined')
   {
      availWidth = window.innerWidth / 10;
   }

For IE 4.0+, document.body.scrollWidth gives roughly the same result.

   else
   {
      availWidth = document.body.scrollWidth / 10;
   }

Having calculated how many spaces we want, we then use a while loop to create a string containing that number of spaces and store it in the variable spaces.

   while (availWidth > 0)
   {
      spaces = spaces + " ";
      availWidth--;
   }

This variable is then concatenated to the front of our message stored in variable message.

   message = spaces + message;

Now that we have our padded message string inside the variable message, we want to make the text look like it is scrolling to the left as shown in Figures 9-9 and 9-10.

Click To expand
Figure 9-9
Click To expand
Figure 9-10

To make this happen, we finish the window_onload() function with a timer that calls a function every 65 milliseconds. This function will move the message across the screen to the left by one character.

   maxLength = message.length - 1;
   setInterval("scrollMessage()",65);
}

So how can this scrollMessage() function make the message move to the left by one character? This is achieved simply by only showing part of the message string. Initially, all of the message string is shown, that is, from character position 0 to maxLength. When the function is next called, only the portion of the string from character position 1 to maxLength is shown. And the next time the function is called, only the portion of the string from character position 2 to maxLength is called.

Eventually all the spaces and most of the words will not be displayed in the status bar, and it will look as if our message has rolled off the left-hand edge.

Once we display just an empty string in the status bar, we start once more by displaying the whole string again. Now we know the principle of how it works, let's look at the following code:

function scrollMessage()
{
   window.status = message.substring(startChar);
   startChar++;
   if (startChar == maxLength)
   {
      startChar = 0;
   }
}

The first thing we do is put our message string into the status bar. However we don't put the whole string in, but instead, using the substring() method, we insert only part of it, the part starting from the character position in the variable startChar and ending with the last character. Remember that with substring() if we don't pass a second parameter with the last character index we want displayed, then we get all the string from the start character to the end.

When the page is first loaded startChar is 0, so our substring will be everything from the first character to the end of the string, or in other words, the whole string. The variable startChar is incremented within the function, so the next time the function is called by the timer, startChar will be 1, so our substring will start from the second character. With each call of the function, the start position gets further along the string, which means that when displayed in the status bar, it appears to the user that the text is moving closer and closer to the left of the window.

Eventually no characters will be displayed in the status bar. This occurs when startChar is the same as the length of the string. Once this point is reached, we need to reset the startChar variable back to zero, giving the appearance of the text starting to scroll from the middle of the status bar again. We do this in the if statement at the end of the function.

That completes our look at this example and also our introduction to timers. Next we're going to use this knowledge to alter the trivia quiz so that it is a time-limit-based quiz.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©

R7