Приглашаем посетить
Добычин (dobychin.lit-info.ru)

Timer Events

Timer Events

Timers fire events after a specified amount of time, rather than as the result of a user action. They are useful for animating objects in the browser or for forcing code to execute after a fixed amount of time. The window object can create two types of timers:

Timers can be added to the window only through code; they cannot be specified as attributes of any element. The setTimeout method creates a timer that executes only once, and the setInterval method creates a timer that repeatedly executes. Both methods take the same set of parameters:

var timerRef = window.setTimeout(script, time)

var timerRef = window.setInterval(script, time)

You can use a one-time timer to repeatedly execute a handler if you reset the timer in the handler, as shown here:

<SCRIPT LANGUAGE="JavaScript">
   var timeEvery100;
   function Every100() {
      // Write code to be executed here.
      // ...
      // Reset the timer.
      timeEvery100 = setTimeout("Every100();", 100);
   }

   // Make first call.
   timeEvery100 = setTimeout("Every100();", 100);

   // When user exits the page, remove timer.
   window.onunload = new Function("clearTimeout(timeEvery100);");
</SCRIPT>

If you use setInterval instead of setTimeout, you don't need to reset the timer in the handler.


NOTE: The setInterval method was introduced in Netscape Navigator 4.0 and Internet Explorer 4.0 as a convenience. If you are writing code to run on down-level browsers, use the setTimeout method instead of the setInterval method.

You can pass parameters to the handler by building the function call string manually. The following code builds a function call with three parameters:

var tm = setTimeout("doThis(" + arg1 + ", 23, " + arg3 + ");", 100);

Timers are created using a setTimeout or setInterval method and can be removed at any point using the corresponding clear method: clearTimeout or clearInterval. Both clear methods take as a parameter the timerRef value returned by the set method. Therefore, when you are setting up a timer, the returned value should be saved in a variable.

In the preceding script example, the timer is cleared in the onunload event when the user exits the page. The onunload event is fired right when the page is about to be removed from memory. This step is optional, but it is good programming practice because it ensures that the browser releases the timer from memory.

Using Timers

This section provides three examples that use timers. The first example demonstrates a timer that navigates to a new page after a specified interval; it uses the setTimeout method because the code is intended to execute a finite number of times. The next two examples use the setInterval method. The second example creates scrolling status bar text using Dynamic HTML to improve on the typical implementation of this common device. The third example creates a ticking clock. Timers are used in many examples throughout this book to create interesting effects.

Automatic Page Navigation

The code on the following page demonstrates a simple timer that navigates to a new page after a specified amount of time. It also gives you a brief glimpse into dynamic contents by displaying an updated countdown.

<HTML>
   <HEAD>
      <TITLE>Countdown</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         var intLeft = 5;  // Seconds until navigation occurs

         function leavePage() {
            if (0 == intLeft)  // Time is up—navigate.
               document.location = "home.htm";
            else {
               // Count down and output updated time by
               // changing the contents of the element.
               intLeft -= 1;
               document.all.countdown.innerText = intLeft + " ";
               // Wait another second.
               setTimeout("leavePage()", 1000);
            }
         }
      </SCRIPT>
   </HEAD>
   <BODY ONLOAD="setTimeout(`leavePage()', 1000)">
      Navigation to <A HREF="home.htm">home.htm</A> will occur in 
      <SPAN ID="countdown">
         <!— Output initial amount of time. —>
         <SCRIPT LANGUAGE="JavaScript">
            document.write(intLeft);
         </SCRIPT>
      </SPAN>
      seconds.
   </BODY>
</HTML>

The number of seconds the timer takes to navigate is controlled by the intLeft variable. Changing the initial value of the intLeft variable also automatically updates the initial value in the contents because of the simple script in the document's body.

Scrolling Status Bar Text

The following code creates status bar text that scrolls from right to left. This example will run only in Internet Explorer 4.0 because the Body element is customized with a user-defined attribute to store the message. This technique of adding attributes to elements to define new behavior is introduced in Chapter 8, "Scripts and Elements."

<HTML>
   <HEAD>
      <TITLE>Scrolling Status Bar Text</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function spacer(pos) {
            // Simple routine to generate spaces
            var space = "";
            for (var i = 0; i < pos; i++) 
               space += " ";
            return space;
         }

         function scrollStatus() {
            // Verify that there is a message to scroll.
            if (null != message) {
               with (message) {
                  // Restart message.
                  if (position < -text.length)
                     position = maxSpace;
                  // Scroll words off left edge.
                  if (position < 0) {
                     position--;
                     window.status = text.substring(-position);
                  }
                  else {
                  // Output preliminary spaces.
                  window.status = spacer(position--) + text;
                  }
               }
            }
         }

         function initMessage() {
         // Constructor for message object
         // Message to display is a required argument.
         this.text = document.body.getAttribute("message");
         // The speed is optional.
         if (null != arguments[0])
            this.speed = arguments[0];
         else
            this.speed = 10;
         // Initial number of prefix spaces
         this.maxSpace = 130;
         this.position = maxSpace;
         // Start timer.
         this.timer = setInterval("scrollStatus()", this.speed);

         return this;
         }
      </SCRIPT>
   </HEAD>
   <BODY ONLOAD="message = initMessage(10);" 
         message="Demo String to Scroll">
      Demo Message Page
   </BODY>
</HTML>

Ticking Clock

Before Dynamic HTML, ticking clocks could be added to documents only through applets, images with complex code, or related tricks. This example demonstrates how to create a ticking clock that exists directly within the HTML document. The following code specifies that the output for the clock be placed inside a Span element with the ID clock. After each tick, the contents of the Span element are replaced with the new time.

<HTML>
   <HEAD>
      <TITLE>Ticking Clock</TITLE>
      <STYLE TYPE="text/css">
         #clock {color:blue; font-size:120%} /* Format the clock. */
      </STYLE>
      <SCRIPT LANGUAGE="JavaScript">
         // Check whether IE4 or later.
         var MS = navigator.appVersion.indexOf("MSIE");
         window.isIE4 = (MS > 0) &&
            (parseInt(navigator.appVersion.substring(MS + 5, MS + 6)) 
               >= 4);

         function lead0(val) {
            // Add leading 0s when necessary.
            return (val < 10) ? "0" + val.toString() : val;
         }

         function buildTime() {
            var time = new Date();
            var ampm = "AM";
            var h = time.getHours();
            // Fix military time and determine ampm.
            if (h > 12) {
               h = h - 12;
               ampm = " PM";
            }
            return lead0(h) + ":" + lead0(time.getMinutes()) + ":" +
               lead0(time.getSeconds()) + ampm;
         }

         function tick() {
            // Replace the clock's time with the current time.
            document.all.clock.innerText = buildTime();
         }
      </SCRIPT>
   </HEAD>
   <!— Start up the timer only if the browser is IE4. —>
   <!— When unloading, remove the timer if it exists. —>
   <BODY ONUNLOAD="if (null != window.tmr) clearInterval(window.tmr);" 
         ONLOAD="if (window.isIE4)
            window.tmr = setInterval(`tick()', 999);">
      <H1>Below is a live, ticking clock programmed entirely in HTML.
      </H1>
      <P>The current time is:
      <SPAN ID="clock">
         <SCRIPT LANGUAGE="JavaScript">
            // Down-level script support;
            // output an initial static time.
            document.write(buildTime());
         </SCRIPT>
      </SPAN>.
   </BODY>
</HTML>

This code runs acceptably on down-level browsers that support scripting. The trick here is the document.write method contained within the body of the document to output the current time in the appropriate position in the stream. In browsers that support Dynamic HTML, the clock will continue to be updated with the correct time. In nondynamic browsers, only the time at which the page was loaded is displayed.


Timer Precision

Timer events cannot be relied on to occur with precise regularity—a timer event designed to fire once per second may not actually do so. Depending on the operating system, the timer may not fire until another application or process yields to the browser.

Irregularity can be visible in a timer that is used for animation. The animation might appear to stop momentarily, rather than move smoothly. This hesitation is probably due to a delay in the timer's execution caused by some other process or by the browser itself.


[Содержание]