How to Start and Stop a setInterval Call in JavaScript?

If you are wondering how to start and stop a setInterval call in JavaScript? Read on to explore new insights!

In this article, we will show you how to use the setInterval and clearInterval ()methods in JavaScript to start and stop a function at a specified time interval.

We will provide a detailed explanation of the syntax, parameters, and return value of these methods, as well as examples of how to use them in practice.

What is setinterval in JavaScript?

The setInterval() is a method in JavaScript that allows you to repeatedly execute a function or a block of code at a specified time interval.

This method returns an ID that can be used to stop the interval using the clearInterval() method.

The first argument of setInterval() is the function or code to be executed, and the second argument is the time interval in milliseconds between each execution.

The interval will continue until clearInterval() is called or the window is closed.

Syntax

setInterval(function, delay, [arg1, arg2, ...]); ✅

Parameter

function (Required)

The function to be executed every delay milliseconds.

delay (Required)

The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code.

arg1, arg2, …(Optional)

Additional parameters to pass to the function specified by callback.

Return value

The setInterval() method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() and passing it the ID value returned by setInterval().

How to stop a setInterval call in JavaScript using clearInterval () method?

To stop a setInterval() call in JavaScript, you can use the clearInterval() method. The setInterval() method returns an ID value that represents the interval object.

You can pass this ID value as an argument to the clearInterval() method to stop the interval.

Here’s an example:

let intervalID = setInterval(() => {
console.log('Hi welcome to Itsourcecode!');
}, 1000);

setTimeout(() => {
clearInterval(intervalID);
}, 5000);

Output:

Hi welcome to Itsourcecode!
Hi welcome to Itsourcecode!
Hi welcome to Itsourcecode!
Hi welcome to Itsourcecode!

In this example, the setInterval() method is used to log ‘Hi welcome to Itsourcecode!‘ to the console every 1000 milliseconds (1 second).

The ID value returned by setInterval() is stored in the variable intervalID. After 5000 milliseconds (5 seconds), the setTimeout() method is used to call the clearInterval() method and pass it the intervalID value.

This stops the interval and the ‘Hi welcome to Itsourcecode!‘ message is no longer logged to the console

How to start and stop a setInterval call in JavaScript?

In JavaScript, you can use the setInterval function to repeatedly call a function at a specified time interval.

The setInterval function returns an ID value that you can use to stop the interval using the clearInterval function.

Here’s the complete example code:

<html>
<style>

            body {

                text-align: center;
            }

        </style>
    <body>
        <h2>How to Start and Stop a setInterval Call in JavaScript? </h2>
        <p id="demo"></p>
        <button onclick="myStartFunction()">Start time</button>
        <button onclick="myStopFunction()">Stop time</button>
    </body>
    <script>
var sampleVar;
function sampleTime() {
    var date = new Date();
    var time = date.toLocaleTimeString();
    document.getElementById("demo").innerHTML = time;
}
function myStartFunction() {
    sampleVar = setInterval(sampleTime, 100); ✅
}

function myStopFunction() {
    clearInterval(sampleVar);
}

 </script>

</html>

The example code above, defines several variables and functions. The myVar variable is used to store the ID value returned by the setInterval function.

The sampleTime function creates a new Date object, gets the current time as a string using the toLocaleTimeString method, and sets the innerHTML property of the element with ID “demo” to the current time.

The myStartFunction function is called when the “Start time” button is clicked. It calls the setInterval function with the sampleTime function and an interval of 100 milliseconds as arguments, and stores the ID value returned by setInterval in the sampleVar variable.

This starts an interval that calls the sampleTime function every 100 milliseconds, updating the time displayed on the page.

The myStopFunction function is called when the “Stop time” button is clicked. It calls the clearInterval function with the ID value stored in the sampleVar variable as an argument.

This stops the interval that was started by the setInterval call in the myStartFunction, stopping the updates to the time displayed on the page.

Output

Conclusion

The setInterval and clearInterval methods in JavaScript provide a powerful way to execute a function or block of code at specified time intervals.

The setInterval method starts the execution and returns an ID that can be used to stop the execution using the clearInterval method.

We have also provided example code that demonstrates how to use these methods to start and stop a clock.

Remember, it’s important to always clear your intervals when they’re no longer needed to prevent unnecessary resource usage.

We hope this article has provided you with enough information to help you understand the stop setinterval in JavaScript.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment