Date object. Timer events.

JavaScript has a special class Date to work with dates and times. This class allows to do a lot of interesting things especially being combined with timers. We'll first discuss these things separately and in the last section we'll consider an example that includes all of them.

Date object.

The Date object is another predefined JavaScript object. It allows us to deal with dates and times and to get certain date/time values. To use such values in our script we first need to create an instance of the Date object:
var current_time = new Date();
A Date instance created the way above will contain the current date and time. If we want to put a specific date/time an object we can use constructors with arguments. These arguments can be like this:
var date_var = new Date("month day, year hours:minutes:seconds");
where the exact date and time is assign by a string containing string values. For example,
var birthday = new Date("December 17, 1995 03:24:00");
We can also use integer values to assign date/time. They should be in the following order:
var date_var = new Date(yr_num, mo_num, day_num, hr_num, min_num, sec_num);
or in shorter format to assign date only:
var date_var = new Date(yr_num, mo_num, day_num);
For example, the following code creates exactly the same date and time as the string example above.
var birthday = new Date(1995, 11, 17, 3, 24, 00);
Please notice that we used 11 for December, because month enumeration starts with zero.

The Date object doesn't have many properties, but it does have quite a large number of methods we can use. You can find the complete list of all methods of the Date object in the official documentation. In this section we shortly discuss some of them. The most interesting methods for us would be methods that allows us to extract information from an instance of the Date object. These methods are:

Methods GetYear() , GetMonth(), GetDate() allow us to extract information about year, month, and day of the month respectively. Let's take a look at the example:
Please notice that method getMonth() returns value less by one than the real month number. It happens because JavaScript starts enumerates months with zero. Thus, we are getting value zero for January, 1 for February, ..., 9 for October, ..., and 11 for December. We can think that method getDay(), which returns the day of the week, does the same thing. It gives 0 for Sunday, 1 for Monday, etc. Here is an example:
Surprisingly, but for dates before year 2000 getYear() returns only two digit year:

Methods getHours(), getMinutes(), and getSeconds() extract information about hours, minutes, and seconds respectively. Please notice that hour information is stored in military format (0 to 23, no am/pm suffix):

Two methods getTime() and parse() do the similar job. Both of them return an integer value that contains the number of milliseconds since January the 1st 00:00.00. The difference between these methods is that method getTime() does it for an existing Date object:

and methods parse() takes a string argument containing a date a returns the number of milliseconds between the first of January 00:00.00:
The number of milliseconds can be used to set a date-time in another Date variable using method setTime():
var somewhen = new Date();
somewhen.setTime( Date.parse("July 28, 1990 04:45"); );
Thus, combining together methods getTime() and setTime() we can easily compute the time difference between two events:
Do not forget that due to the fact mentioned above we have to subtract 70 from number of years.

Setting timer events and their handlers.

Now when we know how to work with date and time we can do different things with it. For example, we can create a clock on our page and make this clock show how much time user spent reading this page. To do such clock we first need to take the start time when user loaded the page by:
var start_time = new Date();
and then once in a period of time take the current time, compute the difference, and display the difference in a desired format:
function display_time()
{
  var current_time = new Date();
  var time_spent = new Date();
  time_spent.setTime( current_time.getTime() - start_time.getTime() );
  var msg = time_spent.getHours() + ":" +
            time_spent.getMinutes() + "." +
			time_spent.getSeconds();
  document.clockform.clocktext.value = msg;
}
We are using usual input text element to display time. In the function above clockform is a name of the form containing the clock text element and clocktext in the name of the element:
<fotm name=clockform>
 <input type=text name=clocktext value="0:00.00">
</form>

So far everything seems very simple, but now we need to think about the next question: how we are going to start function display_time(). The problem here is that we need to execute this function not once and not even twice, but many many times to actually make our clock look like clock, that is we can not run it upon some user event (unless we make user click on a button once in a second ). If we make our function display_time() recursively call itself, then our page won't be able to handle any other event permanently renewing the clock. So, the question we need to know an answer for is "How to execute a function once a given period of time?".

There are two methods of object Window that can help us with this problem. These methods are:

These two methods are very similar. Both of them take two arguments: Both of these methods return a value which is actually a reference to the assigned timer event. How to use this reference we'll explain later. The only difference is that method setTimeout("code", timeout) will execute code code only once after timeout milliseconds as far as method setInterval("code", timeout) will execute code code every timeout milliseconds. For our purposes we can use either of these methods, but if we use method setTimeout(), then we have to reset the timeout inside the display_time() function:
function display_time()
{
  var current_time = new Date();
  var time_spent = new Date();
  ...
  document.clockform.clocktext.value = msg;
  setTimeout("display_time()", 700);
}
...
setTimeout("display_time()", 700); // to execute for the first time

If we decide to use method setInterval(), then we don't even have to modify our function. All we need to do is to insert a line of code:

setInterval("display_time()", 700);
to set the time interval for executing the function display_time(). The real example that contains the code implementing ideas discussed above is a little bit more complicated. The biggest difference we haven't talked about is the necessity to take into consideration the time zone, which can be obtained with method getTimezoneOffset().

The second problem is that we need to stop the timer or interval events and their handlers once we moved from the page to another page. Let's consider a simple example:

<html>
<body>
 <script> setInterval("alert('Hello!')", 3000); </script>
</body>
</html>
A page like this will give a user an alert message every three seconds and there is no way to get rid of this annoying thing until you go to another page or close the browser. Thus, we need a tool to be able to stop timer events and clear their handlers. Methods of the object Window provide such tools. These methods takes just one argument reference returned by setTimeout() (clearTimeout()) or setInterval() (clearInterval()) and clear everything after these events. That is, the correct way to set and clear interval or timeout event would be:
var tmout = setTimeout("display_something()", 100000);
...
clearTimeout(tmout);
or define the event handler for event unload for the element body:
<body onUnload="clearInterval(intrvl);">
...
<script>
 var intrvl = setInterval("do_something()", 2000);
</script>
...

Now we will try to illustrate usage of the timer events with two examples.

Redirect page.

First example will be very simple. Assume you moved your very popular page to another site and now want to put simple redirect instead of the page itself in its old location. You redirect page has to display the message that the real page has been moved, print a link to the new location, and automatically load the real page in several seconds. We know all the pieces of the problem: Let's put all of this together:
...
This page has been moved. You will automatically be redirected to the new location in 7 seconds. If your
browser doesn't support JavaScript of you turned it off <a href="new_location/oldpage">click here</a>.
<script>
setTimeout("location.href='new_location/oldpage'", 7*1000);
</script>
...

Moving string example.

Our second example will be much more complicated. We will create a moving line. A given line will move from right to the left on a screen. When its beginning reaches the beginning point then the first character of the line will disappear and appear at the other end. To create a moving line we'll use usual input element of the text type. We only create a new style for it:
<style>
 .moving_line {
   font-size: 150%;
   color: blue;
   border-top-style: double;
   border-bottom-style: double;
   border-right-style: none;
   border-left-style: none;
   text-align: center;
   width: 100%;
 }
</style>
An element input created with the style above is shown below:
To make the user believe that the line moves we will do the following:
  1. display the original line
  2. cut off the very first character and add it to the end of the line
  3. display the modified line
  4. will keep repeating steps 2 and 3
Applied to the example line it will look like:
 " ** This input text element is created with the style above ** "
 "** This input text element is created with the style above **  "
 "* This input text element is created with the style above **  *"
 " This input text element is created with the style above **  **"
 "This input text element is created with the style above **  ** "
 "his input text element is created with the style above **  ** T"
To implement this we will use method substring() of the String object. This method takes two integer arguments start_index and end_index and returns a substring of the string that uses the method. The substring starts at the start_index and ends, as you can guess, at end_index. Thus, the following code:
takes 5 first characters out of the original string, adds them to the very end of the string, and displays the result. In the example instead of using alert() method we will display the string by assigning the result to the value of the text input element. The only thing we need now is to run code like the one above periodically and increase the value of start_position variable. That is, we need to create a function like this:
var start_position = 0;
var str = "*** This string should be moving ***";

function move_string()
{
  var moving_str = str.substring(start_position, str.length) + str.substring(0, start_position);
  document.moveform.movetext.value = moving_str;
  start_position++;
  if( start_position == str.length )
    start_position = 0;
}
and make this function a handler of a timer event. That is, execute it using setInterval() method:
<script>
 var timerRef = setInterval("move_string()", 200);
</script>
The following example contains the complete code and also adds some features that use clearInterval() method to redefine speed of the line.