codewithjohn.dev
Published on

Understanding the setInterval Function in JavaScript

In this article, we are going to explore the setInterval() function in Javascript.

Javascript allows the execution of the functions at the specified time, regardless of the time of the execution of the program.This capability is particularly useful for handling asynchronous tasks, animation effects, and real-time updates.

There are two methods for executing code at specific times. or to repeat the code at a specific interval. They are:

In this article we are going to explore about setInterval() function in javascript.

JavaScript setInterval()

The setInterval() method is built-in JavaScript method that is used to repeat a block of code at every given timing event. The function takes two parameters the first one is the function to be excuted and the second one is the time interval(in milliseconds) between each execution the setInterval() continues to run until the the clearInterval() method is called or the webpage is closed.

Syntax

setInterval(func, delay, arg1, arg2, ...)

Parameter

  • func - the function you want to call

  • milliseconds - (optional) mount of time in milliseconds to delay each call of the function

  • param1, param2, param3 … (optional) - additional parameters will be passed to the specified function.

Return value

The setInterval() method returns an intervalID which is a positive integer. This ID is an integer value that can be passed as an argument to the clearInterval() function to stop the execution of the interval.

Notice that its syntax is very similar to that of the setTimeout method. However the difference is. For the setTimeout method, the function is only fired once after the timer has expired. However, the setInterval method runs the function repeatedly unless it is cancelled.

Here's an example that demonstrates the usage of setInterval().

example_one.js
function setHellow() {
    console.log('Hello world');
}
setInterval(setHellow, 1000);

Here’s another example that displays time on the web page every 1 second.

example_two.js
Let myVar = setInterval(timer, 1000);

function timer() {
    let d = new Date();
    document.getElementById("timeDisplay").innerHTML = d.toLocaleTimeString();
}

In the above example document.getElementById() gets the element from HTML which has the id as timeDisplay and d.toLocaleTimeString() function gives the current time from the system.

So every 1000 milliseconds which is equivalent to 1 sec. the function is repeatedly being executed so every 1 second the innerHTML of the element will be updated.

When you pass additional parameters to the setInterval() method, these parameters (parameter1, parameter2, etc.) will be passed to the specified function.

Here’s another example with parameters passed.

example_three.js
function sayHello(name) {
    console.log(`Hello, ${name}`)
}

setInterval(sayHello, 3000, "john")

The code above will repeatedly print "Hello john" to the console after 3 seconds.

JavaScript clearInterval

The setInterval() method executes a block of code at every specified time interval. If you want to stop this, function call, then you can use the clearInterval() method. As we mentioned above, The setInterval() method returns id, so you can pass the id to the clearInterval() method. to stop the interval.

The syntax of clearInterval() method is:

clearInterval(intervalID)

Here is another example on clearinterval

example_four.js

let count = 0;

let interval = setInterval(function(){

    count += 1;

    // when count equals to 10, stop the function
    if(count === 10){
        clearInterval(interval);
    }

    console.log(“Count is ” + count);

}, 3000);

In the above program, the setInterval() method is used to display the count variable every 2 seconds. But with every execution, we increment the value of the count variable, so when the count reaches 10, the clearInterval()` method stops the function.

Conclusion

In this article, we have discussed how to use the setInterval methods to schedule the execution of a function. Remember to use clearInterval when you want to stop the execution. of a setInterval function. You can use setInterval to Create dynamic and engaging experiences for your users.

If you're interested in delayed execution of tasks, you might also want to explore the setTimeout().