How To Schedule Timer-Based Callbacks With Example

Introduction

 
In this article, we will look at how the JavaScript timer functions - settimeout, setinterval, and Cleartimeout -- are used to schedule and cancel timer-based Callbacks, with a simple example of a stopwatch program.
 
Brief of settimeout
  • In simple words, it will call any function after the specified time (milliseconds). This specified time is also called a delay.
  • For example - if we specify the delay as 5000, then it will wait for 5 seconds and start to execute the function which was passed as a parameter.
Below is the syntax
 
var id = setTimeout(fn, delay)
  1. First Parameter(fn) => Any function name
  2. Second Parameter(delay) =>  specifies the no. of milliseconds to wait before it starts the execution of the given function
Note

The settimeout function returns a unique ID which can be used to cancel the timer at any time using Cleartimeout which is discussed below.
 
Example- Implemented stopwatch functionality using settimeout
  1. <html>    
  2.     
  3. <head>    
  4.     <script type="text/javascript">    
  5.         window.onload = function() {    
  6.             var startbutton = document.getElementById("btnstart");    
  7.             var stopbutton = document.getElementById("btnstop");    
  8.             var clearbutton = document.getElementById("btnclear");    
  9.             var seconds = 0,    
  10.                 minutes = 0,    
  11.                 hours = 0,    
  12.                 currenttimervalue = 0;    
  13.     
  14.             function CalculateTimerPartsAndDisplay() {    
  15.                 //increment logic    
  16.                 seconds++;    
  17.                 if (seconds >= 60) {    
  18.                     seconds = 0;    
  19.                     minutes++;    
  20.                     if (minutes >= 60) {    
  21.                         minutes = 0;    
  22.                         hours++;    
  23.                     } //end of if(minutes>= 60)    
  24.                 } //end of if(seconds>= 60)    
  25.                 //display    
  26.                 document.getElementById("res").innerHTML = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds ? (seconds > 9 ? seconds : "0" + seconds) : "00")    
  27.                 //recursive    
  28.                 timerlogicintiator();    
  29.             } //end of function CalculateTimerPartsAndDisplay()    
  30.             function timerlogicintiator() {    
  31.                 currenttimervalue = setTimeout(CalculateTimerPartsAndDisplay, 1000);    
  32.             } //end of function timerlogicintiator()    
  33.             //intial call of timer logic    
  34.             timerlogicintiator();    
  35.             //call timer logic when startbutton clicks    
  36.             startbutton.onclick = timerlogicintiator;    
  37.             //stop the watch by using clearTimeout function    
  38.             stopbutton.onclick = function() {    
  39.                 clearTimeout(currenttimervalue);    
  40.             }    
  41.             clearbutton.onclick = function() {    
  42.                 document.getElementById("res").innerHTML = "00:00:00";    
  43.                 seconds = 0, minutes = 0, hours = 0;    
  44.             }    
  45.         } //end of onload function    
  46.     </script>    
  47. </head>    
  48.     
  49. <body>    
  50.     <h1 id="res">00:00:00    
  51.           
  52.       </h1>     
  53.         <input type="button" value="start" id="btnstart" />     
  54.          <input type="button" value="stop" id="btnstop" />     
  55.           <input type="button" value="clear" id="btnclear" />     
  56.        </body>    
  57. <html>   
Output
 
Output
 
Live Demo 
 

Brief of Setinterval

 
It is similar to the settimeout function, but it repeats a call to the same function at a given time.
 

FYI as recap

 
Settimeout won’t repeat the call, it just calls a function only once.
 
Syntax of Setinterval 
 
var id = setInterval(fn, delay);
  1. First Parameter(fn) => Any function name
  2. Second Parameter(delay) =>  specifies the no of milliseconds to wait between each execution.
Note

By using this advantage of setinterval, we can just avoid the recursive call which was implemented in the above settimeout program.
 
Example 
 
This time, we implemented the same stopwatch functionality also using setinterval to differentiate and understand easily.
  1. <html>    
  2.     
  3. <head>    
  4.     <script type="text/javascript">    
  5.         window.onload = function() {    
  6.             var startbutton = document.getElementById("btnstart");    
  7.             var stopbutton = document.getElementById("btnstop");    
  8.             var clearbutton = document.getElementById("btnclear");    
  9.             var seconds = 0,    
  10.                 minutes = 0,    
  11.                 hours = 0,    
  12.                 currenttimervalue = 0;    
  13.             //start of button click logics    
  14.             //call timer logic when startbutton clicks    
  15.             startbutton.onclick = timerlogicintiator;    
  16.             //stop the watch by using clearTimeout function    
  17.             stopbutton.onclick = function() {    
  18.                 clearTimeout(currenttimervalue);    
  19.             }    
  20.             clearbutton.onclick = function() {    
  21.                 document.getElementById("res").innerHTML = "00:00:00";    
  22.                 seconds = 0, minutes = 0, hours = 0;    
  23.             }    
  24.             //end of button click logics    
  25.             function CalculateTimerPartsAndDisplay() {    
  26.                 //increment logic    
  27.                 seconds++;    
  28.                 if (seconds >= 60) {    
  29.                     seconds = 0;    
  30.                     minutes++;    
  31.                     if (minutes >= 60) {    
  32.                         minutes = 0;    
  33.                         hours++;    
  34.                     } //end of if(minutes>= 60)    
  35.                 } //end of if(seconds>= 60)    
  36.                 //display    
  37.                 document.getElementById("res").innerHTML = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds ? (seconds > 9 ? seconds : "0" + seconds) : "00")    
  38.             } //end of function CalculateTimerPartsAndDisplay()    
  39.             function timerlogicintiator() {    
  40.                 currenttimervalue = setInterval(CalculateTimerPartsAndDisplay, 1000);    
  41.             } //end of function timerlogicintiator()    
  42.             //initial call of timer logic    
  43.             timerlogicintiator();    
  44.         } //end of onload function    
  45.     </script>    
  46. </head>    
  47.     
  48. <body>    
  49.     <h1 id="res">00:00:00</h1> <input type="button" value="start" id="btnstart" /> <input type="button" value="stop" id="btnstop" /> <input type="button" value="clear" id="btnclear" /> </body>    
  50. <html>   
 

Brief of Cleartimeout

 
 It is used to cancel the execution at any time using the timerid, which was returned.
 
Syntax of ClearTimeout
 
clearTimeout(id);
 
 

Conclusion

 
I hope the above examples were useful. Kindly let me know your feedback or thoughts.


Similar Articles