Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

This script segment pops up an alert box every three seconds. The displayed message is a number. The first alert box displays the number 0. After three seconds another one displays the number 1. This process continues until the number 10. If you attempt to print the number to the document rather than displaying it in a window (box), an error is generated. The reason for such an error is that by writing to the document after a delay you are trying to change the layout, which has been completed. Another important point is that if the expression provided to the setTimeout() method is a function call, as in this example, and the function requires an argument, then it must a global variable. Local variables do not work, because setTimeout() is a method of a frame or the window object (window is the default value if no object is specified). Nonetheless, you can use a literal as the argument. Bear in mind that setTimeout() requires a string-encapsulated expression. You can embed a local variable in this expression as follows:

var cmd = "foo(" + num + ")"
timerID = setTimeout(cmd, 2000) // or any other time

clearTimeout()

This method, also belonging to the window object, cancels a timeout that was set with the setTimeout() method. It is also a method of the frame or window object, so it is discussed later in detail. At this point, it is important that you know how to use it to cancel a timeout. Its general syntax is:

clearTimeout(timeoutID)

timeoutID is a timeout setting that was returned by a previous call to the setTimeout() method. It must be exactly the same as the one used in the setTimeout() method, because it actually identifies the timeout’s settings according to it.

The setTimeout() method sets a timeout; that is, it executes a statement after a specified amount of time. If you want to cancel the time “bomb” during its ticking, you clear it via this method. If you want to change the amount of time set by the setTimeout() method, you must clear it and then set a new timeout. Here is the previous example enriched by the clearTimeout() method:

<HTML>
<HEAD>
<TITLE>setTimeout() and clearTimeout() methods</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function displayAlert() {
  alert("5 seconds have elapsed since the button was clicked.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Click the button on the left for a reminder in 5 seconds;
click the button on the right to cancel the reminder before
it is displayed.
<P>
<INPUT TYPE="button" VALUE="5-second reminder"
 NAME="remind_button"
 onClick="timerID=setTimeout('displayAlert()',5000)">
<INPUT TYPE="button" VALUE="Clear the 5-second reminder"
 NAME="remind_disable_button"
 onClick="clearTimeout(timerID)">
</FORM>
</BODY>
</HTML>

Time and Date Examples

Times and dates are widely used in scripts to achieve many goals and to create various effects. In this section, we shall introduce a few useful scripts that exercise the concepts learned in this chapter.

A Simple Digital Clock

The time and date methods are useful for computing time values in JavaScript scripts. The following example shows how to use such values to create an attractive graphical clock on an HTML page:

<HTML>
<HEAD>
<TITLE>
JavaScript clock
</TITLE>
</HEAD>
<BODY>
<!-- JavaScript immediate script -->
<SCRIPT LANGUAGE="JavaScript">
<!--

// Copyright 1997 -- Tomer Shiran
// image files needed:
// *******************
// dg0.gif
// dg1.gif
// dg2.gif
// dg3.gif
// dg4.gif
// dg5.gif
// dg6.gif
// dg7.gif
// dg8.gif
// dg9.gif
// dgam.gif
// dgpm.gif
// dgc.gif
// Any set of digit images (0-9), an "am" image,
// a "pm" image, and a colon image, respectively,
// will work with this script.

// instructions:
// *************
// Place all image files in a folder / directory.
// Add this script, including all comments, to
// the desired HTML document. The HTML file must
// be located in the same directory as the image
// files.
document.write(setClock())

function setClock() {
 // initialize accumulative HTML variable to empty string
 var text = ""

 // set standard convention for digit and punctuation images
 var openImage = "<IMG SRC=\"" + getPath(location.href) + "dg"
 var closeImage = ".gif\" HEIGHT=21 WIDTH=16>"

 // initialize time-related variables with current time settings
 var now = new Date()
 var hour = now.getHours()
 var minute = now.getMinutes()
 now = null
 var ampm = ""

 // validate hour values and set value of ampm
 if (hour >= 12) {
hour –= 12
ampm = "pm"
 } else
ampm = "am"
 hour = (hour == 0) ? 12 : hour

 // add zero digit to a one-digit minute as spaceholder
 if (minute < 10)
minute = "0" + minute // do not parse this number!

 // convert minute and hour values to strings
 minute += ""
 hour += ""

 // assign image tags according to the value of hour
 for (var i = 0; i < hour.length; ++i) {
text += openImage + hour.charAt(i) + closeImage
 }

 // assign image tag of colon separator to text variable
 text += openImage + "c.gif\" HEIGHT=21 WIDTH=9>"

 // assign image tags according to the value of minute
 for (var i = 0; i < minute.length; ++i) {
text += openImage + minute.charAt(i) + closeImage
 }

 // assign am / pm image tag to text variable
 text += openImage + ampm + closeImage

 // return accumulative HTML string
 return text
}

function getPath(url) {
 lastSlash = url.lastIndexOf("/")
 return url.substring(0, lastSlash + 1)
}

// -->
</SCRIPT>
</BODY>
</HTML>

Example 14-1 (ex14-1.htm). A simple graphical clock based on time and date methods.


Figure 14-4.  With just a few images and a script you can create a graphical clock with the current time on an HTML page.

Here is a screen shot of the script’s output:

The first part of the script is built of comments including a copyright notice, the needed images, and some instructions. It is important to add these comments to every public-domain script because it is often difficult to guess what a script does and what additional objects are needed, such as images.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us