JavaScript - Lesson 8, Dates and Timers

Lesson objectives

Grandfather clock

The Date Object

There is a special object type which is used to store dates and times. A variable of type Date is declared in a similar manner to an array:

<script language="JavaScript">
var thisDate = new Date();
document.write(thisDate);
</script>

When the variable is declared, it is automatically set to the date and time currently stored in the computer's clock (i.e. "now"). Of course, this will only be the correct date and time if the computer clock holds the right information - it could well be wrong. The example above produced the following output:

Sat Jan 26 10:11:05 UTC 2002

which was the date and time at which I ran the program (the UTC indicates which time zone applies to this computer). Variables can also be initialised to specific dates in much the same way that arrays are initialised:

var birthday = new Date("17 July 1964");

(Note the order in which these items appear, and the fact that there is no "th" or "st" by the date.) In fact, the date is stored inside the computer not in terms of months, days and years, but as the number of milliseconds since a fixed point in time, namely 00:00:00 (midnight) on the 1st January, 1970. You can, of course, use Date variables to represent specific moments before this standard date - they will be stored as a negative number of milliseconds.

This is generally an inconvenient form, but JavaScript provides us with several methods to extract from the date the months part, the day part, the year part and even the day of the week corresponding to that particular date! The method getDate() returns the date in the month, getMonth() returns the month number (with 0 representing January, 1 representing February etc.) and getFullYear() returns the year as a 4-digit figure (1997 rather than simply 97). The method getDay() returns a number for the day of the week, with 0 representing Monday, 1 representing Tuesday etc.

<script language="JavaScript">
var today = new Date();
document.write("According to your computer clock:<BR>");
document.write("The year is " + today.getFullYear() + "<BR>");
var monthName = new Array("January", "February", "March", "April",
                 "May", "June", "July", "August", "September",
                 "October", "November", "December");
var temp = today.getMonth();
document.write("The month is " + monthName[temp] + "<BR>");
document.write("The day is " + today.getDate() + "<BR>");
var dayName = new Array("Monday", "Tuesday", "Wednesday",
                        "Thursday", "Friday", "Saturday", "Sunday");
temp = today.getDay();
document.write("The day of the week is " + dayName[temp] + "<BR>");
</script>

Note how the methods are called. They are tacked on to the end of the variable name, separated only by a full stop. You should be getting used to this way of calling methods now (it is the same as for document.write() and myArray.sort() etc.) There are no parameters to these particular methods.

Usually, whenever an object has a method to "get" a particular value, it has a similar one to "set" that value to some number specified in the program. In this case, if you want to set the date/month/year to a specified value (perhaps changing it from a previous value). The methods each take a single number, as follows:

myDate.setDate(4);    // These instructions set the date
myDate.setMonth(12);  // to 4th December 1966 which is my sister's
myDate.setYear(1966); // date of birth

There is no method to set the day of the week (i.e. no setDay() method) as that is only calculated from the date variable itself.

Getting and setting time values

The Date object is used to store times as well as dates, and the hour, minute, second and millisecond values can be extracted from a Date variable using the appropriate "get" method, or changed using the appropriate "set" method.

To set the hours value of a particular time, use the setHours() method. The hours are according to the 24-hour o'clock so myDate.setHours(13) would set the time to 1 o'clock in the afternoon. Similarly, there are setMinutes() and setSeconds() methods which set the minutes and the seconds of the time. Times are specified in milliseconds, so there is also a setMilliseconds() method which can be used to set the milliseconds part of the time. The following program sets the time value to exactly 30 milliseconds after 5.45 in the evening:

<script language="JavaScript">
var teaTime = new Date();
teaTime.setHours(17); // 17 means 5 o'clock in the evening
teaTime.setMinutes(45);
teaTime.setSeconds(0);
teaTime.setMilliseconds(30);
writeln("The date and time is " + teaTime + "<BR>");
</script>

You won't be surprised to hear that there are methods called getHours(), getMinutes() and getSeconds() and getMilliseconds() which take no parameters and which extract the hours, minutes, seconds and milliseconds from a time. The following program, for instance, declares a variable with the current date and time, and then advances the minute value of the time by 30 minutes - it extracts the minute value, adds 30 to it and then resets the minutes of the time to the new value:

<script language="JavaScript">
var now = new Date();
var minutes = now.getMinutes();
minutes += 30;           // Add 30 minutes to the time
now.setMinutes(minutes); // Reset to new value
</script>

This program does not get confused if adding 30 minutes to the time would "push" the time beyond the next hour. For instance, if the time represented 5.45 in the evening, then adding 30 minutes would correctly set the time to 6.15 in the evening. It would be equivalent to setting the hours value to 6 and the minutes values to 15. Similarly, the following instructions:

myTime.setHours(10);
myTime.setMinutes(75);

actually sets the hours to 11 (not 10) and the minutes value to 15 (not 75). This is because 75 minutes are equivalent to one hour and fifteen minutes. A similar thing happens with dates:

myTime.setMonths(6);
myTime.setDate(40);

These instructions would set the month to 7 (which is August, remember, as the months start counting from 0) and the date to the 9th (as there are 31 days in July, month number 6 according to the computer). Finally, we have a program which displays an alert box exactly three minutes after the program is run. You could use the program to time a soft-boiled egg:

<script language="JavaScript">
var now = new Date();
var s = now.getSeconds();
var m = now.getMinutes();
var h = now.getHours();
m += 3;     // Add 3 to minute count (changes hours if necessary)
now.setMinutes(m);  // Update the minutes
do
 { var t = new Date();  // This keeps getting the current time
 }
while (t.getSeconds() != s || t.getMinutes() != m || t.getHours() != h);
alert("Time's up!");
</script>

Timers

A timer is a special variable which can be set up to keep track of the time according to the computer's internal clock and then cause an event to happen when a certain number of milliseconds have elapsed. You may argue that we have just done that in the previous program - it waits 3 minutes (180 000 milliseconds) and then displays the message. However, there are two differences between proper timer variables and simple timing loops:

  • a timer variable causes an event to happen, similar to the sort of event caused by the user (like ONCLICK). This can be used to trigger a function call, in a similar manner to events that you met with input forms.

  • Unlike a simple timing loop, the program does not pause while the timing is being carried out. It allows the program to continue with other things, and then the event interrupts the program in full flow when the timer reaches the correct point.

There are two types of timer - one-shot timers that activate just once after a certain time, and then die, and regular interval timers that activate regularly at specified intervals until the program finishes or until the program deliberately turns them off.

One-shot timers

The ultimate one-shot timer!

To set up a one-shot timer, declare a variable as follows:

var myVariable = setTimeout("alert('Time has run out!');", 4500);

The variable is an ordinary one - nothing special about the variable name myVariable. However, it is set to a special function. The function setTimeout takes two parameters - firstly, the code which you want executed when the alarm clock goes off (this will normally be a function call, which gives you plenty of freedom) and, secondly, the number of milliseconds between the time when the setTimeout() instruction is carried out and the event is caused.

The example above sets a timer which will run for 4500 milliseconds (4.5 seconds). When the timer runs out (unless it has been turned off by a subsequent instruction), it executes the alert('Time has run out!'); instruction. Note that the message inside the alert() instruction is enclosed within single quotation marks - it has to be as the alert() instruction itself is enclosed within the double quotation marks of the setTimeout() instruction.

Take a look at this pair of instructions:

var x = setTimeout("document.write('ABC');", 60000);
document.write("XYZ");

Note that we include the XYZ of the second document.write() instruction inside double quotation marks. Also, and more importantly, the letters XYZ appear first on the screen - exactly 1 minute (60 000 milliseconds) before the letters ABC appear on the screen. This is because the first instruction sets up the timer, which ticks away in the background, and the program immediately carries on with the instructions that follow. The timer will tick away independently of the main program, and then interrupt the main program - whatever it is doing - when the time runs out. The main program then puts what it is doing on one side, deals with the instruction in the timer command (in this case document.write('ABC');) and then picks up where it left off and carries on.

Suppose you want to cancel a timer once the program has set it up. You put in an instruction like the following:

clearTimeout(x);

In this case, the parameter is the variable name which was used to set the timer up in the first place. In this case, since the parameter is x, the timer that is cleared is the one which carries out the document.write('ABC'); instruction. If you wanted to clear the timer that displays the 'Time has run out' message, then you would use a similar instruction:

clearTimeout(myVariable);

Setting a timer that fires at regular intervals

A slight variation on the instruction produces a timer which doesn't just fire once and then dies, but fires regularly, and carries on doing so until cleared or the web page terminates:

var x = setInterval("do_something();", 52000);

This creates a timer, associated with the variable x, that calls the function do_something() every 52000 milliseconds (every 52 seconds). A function call is the usual instruction that is found when a timer is set up as the function do_something() can be defined to include as many instructions as you like.

The way to clear a regular timer is with a similar instruction to the one above, with clearInterval() replacing the word clearTimeout():

clearInterval(x); // Kills the regular timer off!