JavaScripting for Interactive Educational Webs

[Intro] [Overview] [Basics] [More] [Forms] [If] [Queries] [Time] [Random] [Loops] [Misc.] [References] [HTML]


Time and Timers

Abstract: An introduction to the use of time and timers in JavaScript program, with some emphasis on their use in educational applications, particularly quizzes.


Introduction

Often, we want something to happen to our pages after a period of time elapses. Some "timed changes" we might want include

In addition, we might want to use time in other ways, such as keeping track of how much time students spend on individual pages.

JavaScript provides a number of mechanisms for dealing with time, including a facility for scheduling actions and a time object.


Scheduling Actions

Many of our uses of time relate to scheduling an action at a certain time, or after a particular amount of time has passed. JavaScript permits you to say something like "after N milliseconds have passed, do this".

The function for scheduling operations is setTimeout() and it has the form setTimeout(operation,delay). The delay is in milliseconds.

For example, if I want to bring up a dialog box after ten seconds, I'd use
setTimeout('alert("You may need some help")', 10000)

setTimeout returns a value that we can use at a later date. The primary use of that value is to cancel a scheduled operation, which you do with clearTimeout().

For example, when we load a page, we might start a timer for providing help. When the student clicks a button, we might want to cancel the help (and possibly reschedule it for a later time).


Repeating Actions

Because there are no limitations on the code that is executed, it is possible for the routine called by setTimeout() to schedule additional actions. This repeated use of setTimeout() is often employed in the creation of marquees, clocks, and such.

However, since good design metrics oppose the use of dynamic portions of pages, I will not go into details on this.


The Date Object

JavaScript provides a simple date object for dealing with times. You can obtain the current date/time with

<script language="javascript">
now = new Date();
</script>

The date object provides many methods. Of particular interest are

To determine how long the user spends on the page, you would create a new date object when you first load the page, create another when you leave the page, and compare the values their getTime() method returns.


Loading Other Documents

Often, what we want to do after time has expired is to switch to another page (at least that's what we're going to do in our experiment). To do that, we assign a new url to the location object, as in location="results.html" or location="http://www.math.grin.edu/".


Exercise: A timed quiz.


[Intro] [Overview] [Basics] [More] [Forms] [If] [Queries] [Time] [Random] [Loops] [Misc.] [References] [HTML]

This page written by Samuel A. Rebelsky.

This page generated on 46 by SamR's Site Suite.