Login | Register | FAQ

Lesson 17: JavaScript Timing Events

By Maria Antonietta Perna

The global window object offers a few little functions that are great if you want to create the effect of movement or of passing time on the web.

In this lesson, you will learn about:

  • setTimeout();
  • clearTimeout();
  • setInterval();
  • clearInterval().

In the process, you will also learn how to preload images with JavaScript and how to build a simple photo gallery application.

How do I use setTimeout()?

If your program has a chunk of code that needs to be executed after a specified time, then setTimeout(actionToExecute, timeInMilliseconds) is your function.

Let's see it in action. In this simple example, we will call up an alertbox 2 seconds after page load. Type the code below in enclosing <script> tags on a simple HTML page:

		//Package the code to insert in the
		//timer in a simple function:
		function sayHello()
		//Package the timer into its own function
		function timeGreeting()
		//assign the timer to a variable:
		//you need to do this so the timer can be
		//referenced by another function when you want
		//to stop it:
		var greeting = setTimeout(sayHello, 2000);
		//Notice how the time is set in milliseconds.
		//Now call the timer function

Save your work and run it in a browser. After 2 seconds, an alertbox should pop up to greet you.

How do I use setInterval()?

If you need to execute a chunk of code at specified time intervals, then setInterval(codeToExecute, timeIntervalInMilliseconds) is your function.

To see it in action in its most annoying manifestation, just replace setTimeout with setInterval in the previous example and you're done.

Now you should see an alertbox greeting you every 2 seconds! That's enough, just close that window in your browser and let's modify our script so that we can put a stop to that nuisance.

How do I stop the timer?

JavaScript offers 2 handy methods to get rid of timers: clearTimeout(timerVariable) if your timer uses setTimeOut(), and clearInterval(timerVariable) if your timer uses setInterval(). Let's put clearInterval() to good use right away by stopping that annoying alertbox. First of all, add an inputbox to your HTML page, like so:

<input type="button" value="Stop timer" onclick="stopTimer()" />

Next, rewrite the preceding JavaScript code and then add the new function as follows:

		//Make the variable holding the timer
		//global, so that it can be accessed both
		//by the function setting the timer and by the function
		//stopping the timer:
		var greeting;
		//sayHello() remains unchanged from the previous example
		function sayHello()
		//we increase the time interval
		//to give more time to the user to
		//click the button that stops the alert:
		function timeGreeting()
		greeting = setInterval(sayHello, 5000);
		//package the code that cancels the timer
		//in its own function that will be called when
		//the button on the page is clicked:
		function stopTimer()
		//you call clearInterval() and pass the variable
		//containing the timer as argument

Save your work and preview it in a browser. Just click the button and the annyoing alertbox disappears: that's much better, great! I leave you to experiment with clearTimeout() on your own.

Try out: a photo gallery application

JavaScript timers are often used to produce animation effects on the web. Photo galleries are one of those widely used applications that often employ JavaScript timers.

It's easy to find a number of sophisticated photo gallery widgets on the web, that you can download and readily plug into your own web page.

However, it's still nice to be able to build a simple prototype, just to really challenge yourself with your newly gained knowledge. In any case, your application can be considered a work in progress, something that evolves and grows as your JavaScript programming skills evolve and grow.

At this stage, your photo gallery will consist of a photo container and 2 buttons: one button to stop the gallery, and one button to restart the gallery. As soon as the page loads, the gallery automatically displays its images one at a time every 2 seconds.

You will also need a few images, possibly all of the same size. For this demo, I prepared four 620px X 378px graphics and saved them in their own images folder.

Let's start from the HTML page. This is made of a <div>, an <img> tag, and 2 <input> tags. Also included are: 1) a small style declaration in the <head> of the document to the effect that the <div> element that contains the gallery will be centered and sized to the same width and height as the gallery graphics; and 2) a reference to an external JavaScript file at the bottom of the <body> element of the HTML page. This location is the most appropriate one because we need to make sure the HTML page and, most importantly, the image referenced by the <img> tag, are fully loaded before the script kicks in.

		<!DOCTYPE html>
		<title>Lesson 17: JavaScript Timing Events</title>
		<style type="text/css">
			margin: 0 auto;
			border:2px solid #ccc;
		<h1>Lesson 17: My Photo Gallery</h1>
		<div id="gallery">
		<img src="images/1.jpg" alt="Photo gallery image" id="photo" />
		<input type="button" id="btnStart" value="Restart gallery" />
		<input type="button" id="btnStop" value="Stop gallery" />
		<script type="text/javascript" src="lesson17.js"></script>

Now prepare the lesson17.js file. Your JavaScript code consists of 3 functions:

  1. init() contains initialization routines: it preloads the photo gallery images so that they will be ready for display as soon as the script calls them. In addition, it binds event handlers to the 2 button elements to stop and restart the gallery;
  2. startGallery() displays each graphic in the gallery every 2 seconds;
  3. stopGallery() stops the gallery so that the photo that comes next with respect to the current photo is not displayed.

Furthermore, the code contains a few global variables at the top that need to be accessed by all the functions in the script. Let's get started.

		//Global variables: a reference to the
		//photo currently displayed on the page,
		var curImage = document.getElementById("photo");
		//a variable to store the timer,
		var galleryStarter;
		//a variable to store a true/false value indicating
		//to the program whether the gallery is on or off,
		var isGalleryOn = true;
		//an array containing 4 strings representing the filepaths
		//to the image files in the images folder,
		var images = ["images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg"];
		//an empty array that will be filled with 4 preloaded
		//image objects: the src property of these image objects will correspond
		//to the filepaths contained in the images[] array,
		var preloadedImgs = [];
		//a variable that works as our counter to
		//advance from one image to the next.  It starts at 0.
		var counter = 0;
		//Init() starts with the image preloading routine.
		//First fill the preloadedImgs[] array with a
		//number of image objects corresponding to the length
		//of the images[] array:
		function init()
		for (var i = 0; i < images.length; i++)
		preloadedImgs[i] = new Image();
		//now assign the value of the strings contained in the
		//images[] array to the src property of each image object
		//in the preloadedImgs[] array, using one more loop:
		for (var i = 0; i < preloadedImgs.length; i++)
		preloadedImgs[i].src = images[i];
		//Now, assign event handlers to the 2 buttons
		//to restart and stop the gallery:
		var btnStart = document.getElementById("btnStart");
		var btnStop = document.getElementById("btnStop");
		btnStart.onclick = startGallery;
		btnStop.onclick = stopGallery;
		//Finally, check the isGalleryOn flag is true.  If it is
		//call the function that starts the gallery:
		if (isGalleryOn)
		//Assign the init() function to the onload event
		onload = init;
		//startGallery() contains the functionality
		//to extract the photos from the preloadedImgs[] array
		//for display and to set the timer in motion:
		function startGallery()
		//extract the image filepath using the counter
		//variable as array index and assign it to the src
		//property of the curImage variable:
		curImage.src = preloadedImgs[counter].src;
		//advance the counter by 1:
		counter ++;
		//if the counter has reached the length of the
		//preloadedImgs[] array, take it back to 0, so the
		//photo gallery redisplays the images from the start:
		if (counter == preloadedImgs.length)
		counter = 0;
		//Set the timer using this same function as one
		//of the arguments and 2000 (2 milliseconds) as the other argument.
		galleryStarter = setTimeout("startGallery()", 2000);
		//Signal that the gallery is on to the rest of the program:
		isGalleryOn = true;
		//stopGallery() uses clearTimeout()
		//to stop the gallery
		function stopGallery()
		//signal that the gallery has stopped to the
		//rest of the program:
		isGalleryOn = false;

Save your work and preview it in a browser. You should see something like the page indicated by following the example link above. Try stopping and restarting your gallery.

Questions, questions, questions

I imagine you might be wondering what this business of preloading images is all about. Well, here's a short explanation.

When an HTML page is first loaded, all the resources needed by the page, including external CSS files, scripts, images, videos, etc., are downloaded as well.

In the case of inserting a resource, such as an image, dynamically into an HTML page after the page has fully loaded in the browser, as it's the case with our photo gallery, the following issue might arise: the requested image has to be sent to the client browser by the server, and this might take a few seconds. Although this is not terrible, it might seriously spoil the magic JavaScript effect we intend to create.

Here's where preloading the images in JavaScript comes to the rescue. By doing the preloading routine, the image object is created on page load, and by assigning the image filepath as value to the image object's src property, we make sure that the image we intend to add dynamically to the page is ready to be grabbed by our script for immediate use.

This is the image preloading routine simplified to the bare minimum:

		//Create an Image object:
		var myNewImage = new Image();
		//assign the filepath of your desired image
		//to the src property of the newly created image object:
		myNewImage.src = "images/testimage.jpg";
		//Now myNewImage has been preloaded: your
		//JavaScript can use it, display it, etc. without fear of
		//having to wait too long for a server request.


You've made it to the end of the lesson, congratulations! You've learned a great deal: you can set and stop timers with JavaScript, preload images for dynamic display, and build an automatic photo gallery with JavaScript.

It's time for your break before tackling your next lesson's topic, a major feature of contemporary web applications: AJAX.

Related topics in the RepliesViews
No related topics yet

+ Post a new topic

<< Lesson 16: Useful Tasks (II) – Form Validation

Lesson 18: Making AJAX Calls >>