Today our target is to know how we can time events – a practical usage can be a quiz page that calculates score on the basis of time taken to answer the questions. This article will lead to a working example that tells your visitor the time he spent on your page. To handle this we need to know the following:
  • How can we read system time
  • Some mechanism of knowing when a visitor entered / left your page
  • How to add / subtract time using JavaScript

On Entering A Page

Whenever a web page gets loaded into the browser window, an onLoad event occurs. You can use this event to store the time when a visitor entered your page. The following body tag calls a function named personIn when the document finishes loading: <body onLoad=”personIn()”>

On Leaving A Page

Like onLoad there is an onUnload event. As its name suggests, an unload event occurs when the visitor leaves a page (by clicking a link; closing the window or entering a different site address.) The following body tag calls functions personIn and personOut when the document finsihes loading and when the visitor leaves the page, respectively. <body onLoad=”personIn()” onUnload=”personOut()”>

The Code

<title>Timing two events</title>


<body onLoad="personIn()" onUnload="personOut()">
This page will time your visit. 
 You will be prompted when you will leave the page.


The script part consists of two functions: personIn and personOut that are called by onLoad and onUnload. There are two variables with the names enterD and outD. When the function personIn is called, it sets current date and time into enterD. Similarly when personOut is called, it initializes the outD variable with current date and time. Next, we store the difference between the entering and leaving times. Note the use of getTime() method – we need it because enterD and outD are objects; not numbers. The difference returned to us is in milliseconds. And thus, to convert it into seconds, we have to divide difference by 1000. In the end, an alert box is used to display the result of these calculations.