HTML and JavaScript – Repeating Anonymous Function

This post demonstrates how to use an anonymous function on an html page in order to create a looping action. It is a relatively simple process and the following code is all that is needed to see this in action.

The comments should be pretty self explanatory in this code to see what is being done. Try it yourself!

Notice a few things. If you would like to end or clear the interval you set in JavaScript, there is a function that is clearInterval. Make sure you replace the function name of the one you would like to repeat in the line where you call the setInterval, in this example the name is render.

Should be straightforward. A challenge is for you to use an onClick event to begin and end the interval that you create.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<html>
	<head>
		<title>Repeating Anonymous Function</title>
	</head>
 
	<body>
		This is my text.  I'm going to repeatedly pop-up a message box that tells you how many times it's popped up.
 
	<script	type="text/javascript">
 
		//Our anonymous function declaration (at the end of the html document)
		(function() {
 
			//Set the timer variable
			var intTime = 5000;
			//Create the interval variable;
			var myInterval;
			//Create a counter
			var count = 0;
 
			//Create the interval with render being the function to call and intTime being the interval
			myInterval = setInterval( render, intTime);
 
			//Here is the function that our timer will call
			function render() {
				count += 1;
				alert("Number of Cycles: " + count);
 
				if (count == 10) {
					//The following ends the execution of the interval
					clearInterval(myInterval);
				}
			}
		//Complete our anonymous function
		})();
 
	</script>
	</body>
</html>

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>