JavaScript Lessons

JavaScript setInterval and clearInterval Tutorial

Learn how to run code on a repeating timer with JavaScript setInterval, then stop it cleanly with clearInterval using practical examples.

Serhat ALPASLAN1 min read

javascript setInterval and clearInterval

The javascript setInterval function runs a given function repeatedly at an interval defined in milliseconds.

Let’s look at it with the following example.

var id = setInterval(() => { 
  zamanlayici() 
}, 1000);

function zamanlayici() {    
  var tarih = new Date();    
  var time = tarih.toLocaleTimeString();         
  console.log(time);
}
// if you run the function below, setInterval will stop
function myStopFunction() {
  clearInterval(id);
}

To stop the Javascript setInterval function, you need to call it as clearInterval(). To stop it, you need to assign the setInterval function to a variable.

Share it if it helped

Write a comment