Menu Home

setInterval()

Hi everyone! It’s a timely edition of Boring JavaScript – this time on the setInterval() function, and its mate, clearInterval();

What is ‘setInterval()’?

In a nutshell, it lets you run a function at certain intervals (thus, the name). For example, if you had a function that printed the elapsed time a race was running, you would use setInterval() to say “Run the function ‘printClock’ every second. One the race ended, you would then use clearInterval() to stop JavaScript from running that function at every interval.

Example

We’re going to use code that works in a browser instead of Node because of the game we will show you at the end. To that end, here is the webpage we will be using:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width,initial-scale=1.0">
		<meta name="Description" content="An exciting edition of Boring JavaScript, this time on the setInterval() method.">
		<title>Boring JavaScript - setInterval</title>
	</head>
	<body>
		<h1>Boring JavaScript - setInterval</h1>
		<div id="results"></div>
		<script src="setInterval.js" type="module"></script>
	</body>
</html>

Not much to it – I just want to point out that we are loading our module in Line 13 and we will be printing any results at the <div> in Line 12.

The magic is in the JavaScript, so let’s take a look at the ‘setInterval.js’ module:

const results = document.getElementById('results');

sendText(results, "Before setInterval");
const myInterval = setInterval(setIntervalFunction, 2000);
sendText(results, "After setInterval");

function setIntervalFunction (params) {
	sendText(results, "*** setIntervalFunction has executed ***");
}

function sendText(dom, text) {
	const p = document.createElement('p');
	p.textContent = text;
	dom.appendChild(p);
}

The important code is Line 4, where you see the “setInterval()” method coded. It takes two arguments:

  1. The function to call. This function must be defined somewhere in your code.
  2. The interval between calls. This is expressed in milliseconds (1000 milliseconds = 1 second).

setInterval() will return a handle back to you. We’re not using it right now, but it is very important, as you will see later.

In the example above, we will be calling the function “setIntervalFunction” once every 2000 milliseconds, or once every 2 seconds. “setIntervalFunction” merely appends the message in Line 8 to the “results” div.

If you brought this up in a browser, you will see the following:

The browser after loading the page

Hooray! Everything worked as expected, right?

Right?

Well, not quite. You see, that message will print out once every 2 seconds forever. Until you refresh your screen, or close the browser, or turn off the computer. In many instances, you need a way to stop the interval from occurring until the end of time.

clearInterval()

Remember when I said that the handle returned by setInterval() was important? Here’s is why it’s important.

If you ever want to stop a setInterval() from running until the cows come home, pass the handle as an argument to the clearInterval() function. Where setInterval() starts running a function at an interval, clearInterval() will stop it. All you need is the handle to that interval.

Here is the changed code:

sendText(results, "Before setInterval");
const myInterval = setInterval(setIntervalFunction, 2000, params);
sendText(results, "After setInterval");

function setIntervalFunction (params) {
	sendText(results, "*** setIntervalFunction has executed ***");
	params.count++;
	if (params.count >= 5) {
		clearInterval(myInterval);
		sendText(results, "------- setIntervalFunction has stopped -------");
	}
}

Notice two things:

  1. We’re passing a third argument to setInterval() (Line 2). This argument will be passed to the function declared in the setIntval() declaration, and that is why you see “params” as the argument to the “setIntervalFunction”. You don’t really need it in this case – I just added it to show it can be done.
  2. Using “params.count”, we are now checking if the count reaches five. Once it does, we issue the clearInterval() method to stop the process.

And here is the result:

The browser output after the second example

And now the function stops executing after five rounds!

The Game

When I was doing this Boring JavaScript code, I found out there wasn’t much there. I thought – well, then let’s show a real world application. And what better real world application than – A GAME!

The game I came up with in the space of an hour is a very simple Whack-A-Mole style game. Here is a screen shot:

The Boring JavaScript setInterval() Game

Here’s what happens in the game.

  1. Click on ‘Click to Start’. This will begin a five-second countdown.
  2. When the countdown gets to ‘0’, a buzzer will sound.
  3. A bar with one of four colors will appear under the text ‘Click to Start’, and the text itself will change to the name of the color.
  4. You then have to click on that color in one of the four small boxes under ‘Click to Start’. If you click correctly, your score increments and appears in the number to the far left. Another color will appear, and you continue the process.
  5. You have 10 seconds to click on as many colors as possible. Once 10 seconds is done, a buzzer sounds and the game is over.

It’s a very simple game that uses two setInterval() functions – one for a countdown from 5 (before the game begins) and one to run the 10-second clock you see in red above.

I won’t go into details here, but I encourage you to visit our GitHub site at https://github.com/TheVirtuoid/boringjavascript, go to “J023-setinterval”, and download the game yourself. It’s your to keep and fool around with.

The Video

Here is the Boring JavaScript video where I cover the above and the game.

Conclusion

Remember these points:

  1. setInterval() requires a function to execute at each interval, and the interval itself. The third parameter is optional.
  2. The interval is in milliseconds. There are 1000 milliseconds in one second.
  3. Save the handle returned by setInterval()! You will need it to pass to clearInterval() or your function will fire forever.

setInterval() and clearInterval() are quick and convenient methods for creating timers in JavaScript. If you have any type of timing in your application, they are great tools to have in your arsenal.

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: