setInterval()
method executes a specified function multiple times at set time intervals specified in milliseconds (1000ms = 1second).setInterval()
method will keep calling the specified function until clearInterval()
method is called or the window is closed.setInterval()
method returns an ID which can be used by the clearInterval()
method to stop the interval.setTimeout()
method.Usage of JavaScript setInterval
JavaScript interval to be set use setInterval()
function. It could be defined simply as a method which allows you to invoke functions in set intervals.
The JS setInterval()
function is similar to the setTimeout method. How are they different? Well, setTimeout()
calls functions once. However, with the set interval method you can invoke them multiple times.
Let’s say you need to display a message to your website visitors every 3 seconds. By applying the JavaScript setInterval()
function, you will be able to perform this task and incorporate a new feature on your website.
However, we would recommend not to overuse this function as it might disrupt the overall user experience. The following code example shows the way the message is set to be displayed every 3 seconds:
Example
setInterval(() => {
alert("Hello");
}, 3000);
In this video I show you how to use the inbuilt JavaScript method setInterval() in a simple theoretical example, and then a more complex production example, using my game of whack-a-mole.
#javascript #programming