You are on page 1of 7

DCIT 65 – Web Development Lecture # 8

JavaScript Timing Events

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:
 setTimeout() - executes a code some time in the future
 clearTimeout() - cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.
The setTimeout() Method

Syntax
var t=setTimeout("javascript statement",milliseconds);

The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want
to cancel this setTimeout(), you can refer to it using the variable name.

The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement
like "alert('5 seconds!')" or a call to a function, like "alertMsg()".

The second parameter indicates how many milliseconds from now you want to execute the first parameter.

Note: There are 1000 milliseconds in one second.

Example
When the button is clicked in the example below, an alert box will be displayed after 5 seconds.

<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
</script>
</head>
<body>
<form>
<input type="button" value="Display timed alertbox!" onClick="timedMsg()" />
</form>
</body>
</html>

1 Prepared by: Ms. Steffanie D. Maglasang


DCIT 65 – Web Development Lecture # 8

Example - Infinite Loop

To get a timer to work in an infinite loop, we must write a function that calls itself.

In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.

Notice that we also have a function that checks if the timer is already running, to avoid creating additional timers, if the
button is pressed more than once:

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

The clearTimeout() Method

Syntax
clearTimeout(setTimeout_variable)

2 Prepared by: Ms. Steffanie D. Maglasang


DCIT 65 – Web Development Lecture # 8

Example
The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a
"Stop Count!" button that stops the timer:

<html><head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script></head><body><form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form></body></html>

Changing Select element content on the fly

Changing a select element's content on the fly is a powerful feature of JavaScript that's just as practical. It forms the basis
of implementing inter-dependant select menus, where the selection of one menu changes the contents of another.

The basic technique

The basic technique for changing a select element's content using JavaScript is a two part process. I'll use the following
SELECT element as an example:

3 Prepared by: Ms. Steffanie D. Maglasang


DCIT 65 – Web Development Lecture # 8

<form name="myform">
<select name="master" size="1">
<option value="newsvalue">News</option>
<option value="webmastervalue">Webmaster</option>
<option value="techvalue">Tech</option>
</select>
</form>

To change "master"s content using JavaScript, do the following:

1) Remove all options by setting the Options array's length to 0


document.myform.master.options.length=0

Doing the above instantly empties the select element, ready to be populated with new data.

2) Repopulate the select menu with new options (aka content), using the Option() constructor on each option:
document.myform.master.options[0]=new Option("Sports", "sportsvalue", true, false)
document.myform.master.options[1]=new Option("Music", "musicvalue", false, false)
document.myform.master.options[2]=new Option("Movies", "moviesvalue", false, false)

The select menu is now repopulated with 3 new entries ("Sports", "Music", and "Movies").

In case you're wondering, the Option() constructor supports the following four parameters, the later two optional:

new Option(text, value, defaultSelected, selected)

Looping through and changing select element content

When repopulating a select element's content, you may want to use a loop instead of changing each option one by one.
Furthermore, the total number of options may not be known in advance (such as 3 above), so you need a dynamic way
to add new options to select. In this case, use the below:

var master=document.myform.master
for (i=0; i<somevariable; i++){
master.options[master.options.length]=new Option(...)
}

The key here is the property "options.length", which automatically adds 1 to the current length of the select element.
This lets you add new options to the end of the select element without knowing any info about its existing length.

Removing a single option within select

Moving on, you can also selectively remove a single option without performing mass destruction on all options within
select first. This is done by setting the desired option to null. Doing so removes the option from the list, with the options
below it moving up to occupy the void:

document.myform.master.options[1]=null

4 Prepared by: Ms. Steffanie D. Maglasang


DCIT 65 – Web Development Lecture # 8

Removing multiple options (from the end of the list)

You can also easily remove multiple options from select, provided they are at the end of the list. Simply set the Options
Array's length to something smaller than its current length, and say bye bye to options that fall after the new length in
index:

document.myform.master.options.length=1

This removes all options within the select except for the very first one.

5 Prepared by: Ms. Steffanie D. Maglasang


DCIT 65 – Web Development Lecture # 8

6 Prepared by: Ms. Steffanie D. Maglasang


DCIT 65 – Web Development Lecture # 8

7 Prepared by: Ms. Steffanie D. Maglasang

You might also like