Timing Function

The JS window object provides two build in timing functions, setInterval and setTimeout to repeat a function after certain time duration or to run a function once after certain time. Even HTML5 introduced a new timing function requestAnimationFrame to run smoother animations, mainly used in HTML5 Canvas.


setInterval

The Javascript setInterval method repeat a function after given time. The first parameter of setInterval is function name and second parameter is time (in milliseconds). As setInterval is a JS build in function, so no need to invoke function name in setInterval. See example

setInterval Example

<script>

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

Counter using setInterval

0


    var counter=0;
    function increaseCounter(){
    counter++;
    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. See example

setTimeout Example


  function myAlert(){
    alert("hey there");
  }                    
  setTimeout(myAlert,1000)  
  // run function after every 1 second
                

call a function after sometime




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

clearInterval

clearInterval function is used to stop setInterval and setTimeout functions for further executions. The parameter in clearTimeout function is either id of setInterval/setTimeout or variable name of setInterval/setTimeout functions. See example


  var counter=0;
   function setTimmer(){
   console.log(counter);
   counter++;
   }
  setInterval(setTimmer,1000);    // returns an integer id
  
    clearInterval(id);     // stop setTimmer function  

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

clearInterval Example

0


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