Electric Type

Multimedia

About Us

News

Help

Advanced JavaScript Tutorial
Lesson 3

by Thau!

Page 4 — Timing Loops - How to Do Them

To get a timer working in a loop, you have to write a function that calls itself. Happily, this is possible in JavaScript. Here's an example:

var the_count = 0;
var the_timeout;
function doTimer()
{
	window.document.timer_form.the_text.value = the_count;
	the_count += 2;
	the_timeout = setTimeout("doTimer();", 2000);
}

This is the timer that was used on the previous page. When a user clicks on the button, it calls this function, which in turn writes the current value of the_count to the textbox. It then increments the_count by two, and then calls itself in a setTimeout. In two seconds, the setTimeout is executed, cleared, and the function runs again. It changes the value in the textbox, increments the_count, and again uses setTimeout to call itself in two seconds. During those two seconds, the browser just sits around, doing the things that browsers do. When two seconds pass, the function runs again. And another setTimeout() is set once the_count is incremented by two. You don't run out of memory because there's only one setTimeout() running at any given time.

This works, whereas the infinite hell-freezing-over loop on the last page didn't, because infinite "while" loops lock the browser up and prevent anything from happening during the execution of the loop. This setTimeout trick makes sort of a slow loop. In the above example, the browser has two seconds to do things between each iteration.

How to Cancel a setTimeout

Now that you know how to make a timer loop run infinitely, you'll probably want to know how to stop it. This is the magic of clearTimeout. If you look at the HTML of the timer on the previous page, you'll see the following form element:

<input type="button" value="stop timer"
 onClick="clearTimeout(the_timeout);">
This is the button you hit to stop the timer. The command to stop a setTimeout is clearTimeout(), which is actually quite simple. When you set a setTimeout like this,
the_timeout = setTimeout("some javascript",3000);
you can cancel it like this:
clearTimeout(the_timeout);
Simple, no? Now let's take a look at a slightly more complicated looping timer: one that actually tells time!

next page»


Tutorials  

User Blogs  

Teaching Tools  

Authoring  

Design  

Programming help  

Advanced Flash  

Javascript  

Glossary  

PHP Coding  

User Blogs

Screen Shots

Latest Updates

Contact Us

Valid HTML 4.01!
Valid CSS!

Breadcrumb

© ElectricType
Maintained by My-Hosts.com
Site map | Copyright | Disclaimer
Privacy policy | Acceptable Use Policy
Legal information.