Skip to content
the poor coder

Stop setInterval call in JavaScript

Poor Man
Published
Reading time
1 min read
On this page

Stop setInterval call in JavaScript#

If you want to stop the execution of setInterval function in JavaScript, you can use the clearInterval() method. It clears the interval which has been set by the setInterval() method.

Syntax#

Text
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
clearInterval(intervalID);

The clearInterval() method takes an intervalID parameter, which is the ID returned by the setInterval() method. When you call clearInterval() with the intervalID, it stops the interval from executing.

Example#

Text
var intervalID = window.setInterval(myFunc, 1000);

function myFunc() {
  console.log('Hello World!');
}

// Stop the interval after 5 seconds
setTimeout(function() {
   clearInterval(intervalID);
}, 5000);

In this example, we set an interval to execute the myFunc() function every 1 second. Then, we use the setTimeout() method to stop the interval after 5 seconds.

Another Example#

Text
function startTimer() {
  var count = 0;
  var timer = setInterval(function() {
    console.log(count);
    count++;
    if(count === 10) {
      clearInterval(timer);
    }
  }, 1000);
}
startTimer();

In this example, we create a startTimer() function that sets an interval to execute a function every 1 second. The function logs a count variable to the console and increments it by 1 on each execution. When the count reaches 10, we call clearInterval() to stop the interval.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC