JavaScript Timing Function

JavaScript includes two built-in timing functions, setInterval and setTimeout to call a function after certain time duration or to run a function repeatedly after certain time. Even HTML5 introduced a new timing function requestAnimationFrame to run smoother animations, mainly used in HTML5 Canvas.

Both setInterval and setTimeout have callback functions for asynchronous programming with optional timing. This means a callback function in setInterval or setTimeout will be called after the main thread is free and will not block code.

The reason for asynchronous operations of timing functions is the JavaScript Event loop. The Event Loop executes timing function callbacks after the time is over.


setInterval

The JavaScript setInterval method repeatedly calls a function until it's stopped. The first parameter of setInterval is the function name and the second parameter (optional) is the time (in milliseconds). As setInterval is a JS built-in function, so no need to invoke the function name in setInterval. See example


  setInterval( callback , [ delay, arg1, arg2, ... ] );
          

In the example above, callback is compulsory and other parameters like delay and arguments are optional.

setInterval Example

<script>

    function myAlert(){
      alert("my alert");
    }                  
    setInterval(myAlert,1000)  
    // repeat function after every 1 second                     
</script>                              

Counter using setInterval

0


let counter=0;
function increaseCounter(){
  document.querySelector("p").innerHTML=++counter;
}

setInterval(increaseCounter,1000);

setTimeout

setTimeout method is used to call a function once but after a delay of some seconds. The first parameter of setTimeout method is function name and second is time in milliseconds.


setTimeout( callback , [ delay, arg1, arg2, ... ] );

In the example above, callback is compulsory and other parameters like delay and arguments are optional.

setTimeout Example


function myAlert(){
  alert("hey there");
}                    

setTimeout(myAlert,1000);   // run function after 1 second

call a function after 1 second




function timeOut(){
document.querySelector("p").innerHTML="Hey, how do you do?";
}
setTimeout(timeOut,1000);                             
                  

clearInterval

clearInterval and clearTimeout functions are used to stop setInterval and setTimeout functions from further executions. The parameter in these functions is either the ID of setInterval/setTimeout or the variable name holding the ID. See example


let counter=0;
function setTimer(){
   console.log(++counter);
}

setInterval(setTimer,1000);    // returns an integer id
  
clearInterval(id);     // stop setTimer function 


  let counter=0;
   function setTimer(){
   console.log(++counter);
   }
  let t1=setInterval(setTimer,1000);   
  
   clearInterval(t1);     // stop setTimer function  

Stop Watch

0


let counter=0;

document.querySelector("#btn3").addEventListener("click",function(){
    
  function increaseCounter(){
    document.querySelector("#counter3").innerHTML=++counter;
  }
  let t1=setInterval(increaseCounter,1000);

  document.querySelector("#btn4").addEventListener("click",function(){
    clearInterval(t1);  
  })        
});

requestAnimationFrame

The requestAnimationFrame method is used to create smoother animations in the browser. It tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback function as an argument to be invoked before the repaint.


function animate(){
   // animation code here
   requestAnimationFrame(animate); // calls animate before next repaint
}
requestAnimationFrame(animate); // start the animation

Simple Animation using requestAnimationFrame

Your browser does not support the HTML5 canvas tag.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = 0;
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(x, 50, 50, 50); // draw square
  x += 2; // move square
  if (x > canvas.width) x = 0; // reset position
  requestAnimationFrame(draw); // request next frame
}
requestAnimationFrame(draw); // start animation

Summary

JavaScript timing functions like setInterval and setTimeout enable asynchronous execution of code after specified delays or at regular intervals. setInterval repeats a function call, while setTimeout executes it once. Use clearInterval and clearTimeout to stop these timers. These functions are essential for creating animations, polls, and delayed actions without blocking the main thread, leveraging the event loop for smooth performance.

use requestAnimationFrame for smoother animations as it synchronizes with the browser's refresh rate, providing better performance and smoother animation.