Example of calling a JavaScript function every second

The second solution proposes using setTimeout instead of setInterval to have the ability to stop the animation using clearTimeout and a variable. However, it is important to note that this solution does not work on Internet Explorer. The HTML and pure JavaScript code for this solution is provided. Additionally, the first solution highlights that 1000ms is equivalent to 1 second and 60000ms is equivalent to 60 seconds.


It is necessary to obtain a reference to the timer and terminate it when the mouse button is released.

var timer = null; // Will hold a reference to the timer

 // Set the timer reference
 timer = setInterval(function() {
   console.log("Function running");
 }, 1000);

 clearInterval(timer);  // Cancel the timer
 console.log("Timer cancelled.");

Frequently Asked Questions