clearinterval in javascript

Clearinterval in Javascript

If you are working on a project where you need to execute a specific function or a piece of code repeatedly after a certain time interval, setInterval() function in JavaScript can be your savior. setInterval() method is used to execute a specific function or a piece of code multiple times, with a fixed or variable time interval between each execution.


var intervalID = setInterval(function, milliseconds);

The setInterval() function takes two parameters:

  • A function that will be executed by setInterval() method after every given interval.
  • The time interval between each execution of the function in milliseconds.

However, there might be situations where you need to stop the execution of setInterval() method before it completes all the iterations. For example, if a user performs an action that requires the function to stop executing. In such cases, you can use clearInterval() function.



The clearInterval() function takes only one parameter:

  • The ID value returned by setInterval() function when it was called.

Once you call clearInterval() function with the ID value of the setInterval() function, it stops the execution of the setInterval() function immediately.

Example Code

// Declare a variable to hold the ID value of setInterval() function
var intervalID;

// Execute a function after every 1 second using setInterval() method
intervalID = setInterval(function(){
    console.log("Hello World!");
}, 1000);

// Stop setInterval() function after 5 seconds using clearInterval() function
}, 5000);

In the example code, setInterval() function is used to execute a function that logs "Hello World!" in the console after every 1 second. After 5 seconds, clearInterval() function is called using the ID value returned by setInterval() function to stop its execution.

Hope this explanation helps you understand how setInterval() and clearInterval() functions work in JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]