Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

Contact Us or call 1-877-932-8228


Timers are started and stopped with the following four methods of the windows object:

  1. setTimeout(code_to_execute,wait_time_in_milliseconds)
  2. clearTimeout(timer)
  3. setInterval(code_to_execute,interval_in_milliseconds)
  4. clearInterval(interval)

Let's take a look at how setTimeout() and clearTimeout() work first:

Code Sample:

<meta charset="UTF-8">
	var timer;
	function changeBg(color) {
		timer = setTimeout(function() { document.body.style.backgroundColor=color; }, 1000);	
	function stopTimer() {
<button onclick="changeBg('red')">Change Background to Red</button>
<button onclick="changeBg('white')">Change Background to White</button>
<button onclick="stopTimer()">Wait! Don't do it!</button>

Code Explanation

Things to notice:

  1. We make timer a global variable so that we can access the timer object from within multiple functions.
  2. In the changeBg() function, we create the timer. Note that we need to place document.body.style.backgroundColor=color in a function; otherwise, the code will execute immediately. In this case, we use an anonymous function, which works just like a regular function. Note that because the function is nested within the changeBg() function, it has access to the local variable color.
  3. The stopTimer() function simply clears the timer timer using clearTimeout().

The setInterval() and clearInterval() methods work the same way. The only difference is that the code gets executed repeatedly until the interval is cleared.


This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.