How to stop JavaScript setInterval() after a certain time period?

By Faruque Ahamed Mollick

We have already learned how to run our JavaScript code every n seconds periodically. Now in this tutorial, we are going to see how to stop the JavaScript setInterval() method from running our code or function after a certain time.



JavaScript has a method clearInterval() method that stops the setInterval method from executing the JavaScript code inside the setInterval method. But the problem is that this method will immediately stop the setInterval method. We want our code by the setInterval method at least for few seconds and after that, it should stop it’s periodic behave.

Set a default image for broken or Unavailable image URL in JavaScript

Well, there is a solution. We will the JavaScript setTimeout method which will delay in running our clearInterval() method for few seconds. In this example, we will delay calling our clearInterval() method 12 seconds. So after 12 seconds, our setInterval method stop running the code again and again. Below is our JavaScript code:

  // Get the Interval ID
var setInterval_ID = setInterval(my_alert_func, 2000);

function my_alert_func()
{
  alert('I am an alert message appear in every 3 seconds');
}

  // Set timeout to call stop_interval function after 12 seconds
  setTimeout(stop_interval, 12000);

  function stop_interval()
  {
  	clearInterval(setInterval_ID);
  }
  

If we run the above code, then it will run our alert message and after 12 seconds the setInterval() method will stop running the alert message and we will no more able to see the alert message.

Copy text to clipboard on click using JavaScript

Disable right click, copy, cut on web page using jQuery

Actually, setInterval() returns an interval ID, which we pass to clearInterval() to stop that setInterval method from running the code. Thus we are being able to stop setInterval() method from running our JavaScript code after a certain time or after few seconds.

Leave a Reply

Your email address will not be published. Required fields are marked *