Timers

Allows JavaScript to be run at specified times.

 

setTimeout()

Runs once.

Requires:

  • Name of function to run
  • Duration in milliseconds

An alert is shown after 3 seconds:

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
		<script>
			function myAlert(){
				alert("This is a delayed message.");
			}
			setTimeout(myAlert, 3000);
		</script>
	</body>
</html>

 

setInterval()

Repeats specified function at the specified interval duration.

Requires:

  • Name of function to run
  • Duration in milliseconds

Initial image is shown, and then changed to the next array index value every 3 seconds:

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
		<img id="myImage" src="1.jpg"/>
		<script>
			var myImg = document.getElementById("myImage");

			var imgArr = ["2.jpg", "3.jpg", "4.jpg", "5.jpg", "1.jpg"] ;

			var imgIndex = 0;

			function chgImg(){
				myImg.setAttribute("src",imgArr[imgIndex]);
				imgIndex++;
				if (imgIndex >= imgArr.length) {
					imgIndex = 0;
				}
			}

			setInterval(chgImg, 3000);
		</script>
	</body>
</html>

 

 

clearTimeout() and clearInterval() are the complementary functions of the above setTimeout() and setInterval() functions, that allow us to clear the previously set timers.

 

For example, setInterval() also returns a value which we can store in a variable, which we can then use within the clearInterval() function. This example uses the onclick event to clear the setInterval timer and hence stop the images changing:

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
		<img id="myImage" src="1.jpg"/>
		<script>
			var myImg = document.getElementById("myImage");

			var imgArr = ["2.jpg", "3.jpg", "4.jpg", "5.jpg", "1.jpg"] ;

			var imgIndex = 0;

			function chgImg(){
				myImg.setAttribute("src",imgArr[imgIndex]);
				imgIndex++;
				if (imgIndex >= imgArr.length) {
					imgIndex = 0;
				}
			}

			var myIntervalHandle = setInterval(chgImg, 2000);

			myImg.onclick = function(){
				clearInterval(myIntervalHandle);
			}
		</script>
	</body>
</html>

Leave a Reply