By | August 8, 2013
In JavaScript timer is the most important feature, it allows us to execute JavaScript function after a specified period; thereby, making it possible to add a new dimensions, time, to our website. With the help of timer , we can run a command at the specified intervals, run loops repeatedly at a predefined time, and synchronize multiple events in a particular time span.

There are various methods for using it:


           1.      The setTimeout() method:  Executes code at a specified interval. Syntax for this : 
                                                           setTimeout(function, delayTime)
In the above syntax the setTimeout() method contains two parameters – function and delayTime. The function parameter specifies the method that the timer calls and the delayTime parameter specifies the number of milliseconds to wait before calling the method.

Example :Let’s try with an example, this method is useful when we want to delay the execution of a particular code.  Let’s write a code :

The setTimeout(“alert(‘Hi, Welcome! Ankur Here.’)”, 5000) method is used to create a timed alert box. The first parameter of the setTimeout() method is a string that contains a JavaScript statement, alert(‘Hi, Welcome! Ankur Here.’), and 2ndparameter , 5000 , specifies the time in milliseconds after which the first parameter will esecute.
So output of this code will be:



      2.      The clearTimeout() method:  Deactivates or cancels the timer that is set using the setTime() method.    Syntax for this :
clearTimeout(timer)

in the above syntax , timer is a variable that is created using the setTimeout() method.
      3.      The setInterval() method : Executes a function after specified time interval. The syntax for this :
setInterval(function, intervalTime)

In above syntax the setInterval() is the method contains two parameters- function and intervalTime. The function parameters specifies the method to be called; whereas, the intervalTime parameter specifies the time interval between the function calls.
Example :Let’s try with an example, this method is used to execute the code after every specified time intervals.  Let’s write a code:




In given code the setInterval() method is used to create a timer that calls the alert() method repeatedly. In the setInterval() method, the first parameter is a string that contains a JavScript statement, alert(‘Sorry ! 1 seconds.’). The second parameter specifies the time in milliseconds, 1000, after which the first parameter is displayed.

So the Output of this code will be :

      4.      The clearInterval() method: Deactivates or cancels the timer that is set using the setInterval() method.     The syntax for this :
clearInterval(timer)
The preceding syntax deactivates the inner timer variable that is created using the setInterval() method.

So Enjoy and work with Timer in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *