Timers

Contact Us or call 1-877-932-8228
Timers

Timers

Timers are started and stopped with the following four methods of the window 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:

ImagesWindowsTimers/Demos/Timer.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Timer</title>
<script type="text/javascript">
	var timer;
	function changeBg(color) {
		timer = setTimeout(function() { document.bgColor=color; }, 1000);	
	}
	
	function stopTimer() {
		clearTimeout(timer);	
	}
</script>
</head>
<body>
<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>
</body>
</html>

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.bgColor=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.

Next