How to implement timing events in javascript

0
4052

In this session we will learn how to implement timing events in javascript .

  • There are two methods used in JavaScript which will help us learn how to implement timing events in javascript :
    1. setInterval() :- This method will execute every time after specified milliseconds.

    2. setTimeout() :- This method is executed only once after completing the specified interval of time

  • Let’s study these methods in detail

  1. setInterval() function
    1. The setInterval() method will wait for a given number of milliseconds i.e. it will wait for the number of milliseconds specified in its parameter and after that it will execute the function after every regular intervals as specified .
    2. Create a new html file and write the following code which will display the current time and date :
    3. Here is the screen shot of the code :
    4. how to implement timing events in javascript 1

    5. Now double click on your html file and you will have following output :
    6. timing event 2

    7. Here is the explanation of the timer() function used in the code :
      1. Variable d is used to make the object of the class Date
      2. Current time is stored in variable t .
      3. The current date is stored in the variable c through the object d which calls the method of class Date known as toLocaleDateString()
      4. The next two lines are used to display the current time and date .
      5. var setTime=setInterval(function(){timer()},500) In this code the setInterval method is used to start the timer after the interval of 500 milliseconds i.e. half seconds.

    8. Now if we want to stop the time for the function setInterval then we have to use the clearInterval method .
    9. clearInterval method is used to stop the further execution of setInterval method .
    10. This can be explained with reference to the above code just by adding a button and stop function which is used to stop the time.
    11. Here is the screen shot of the updated code with stop functionality :
    12. javascript timing events 3

    13. Output is shown below :
    14. timing events4

  2. setTimeout() function
    1. The setTimeout method is used to provide an interval for the specified time and is executed only once .
    2. Here is an example that implements the setTimeout() function :
    3. Screen shot of the code is given below :
    4. javascript 5

    5. Now when you double click on your setTimeout.html file you will have the following output :
    6. 6
      7
      how to implement timing events in javascript 8

  3. Thus we have successfully learnt how to implement timing events in javascript and implemented setInterval() and setTimeout() functions in javascript .

LEAVE A REPLY

Please enter your comment!
Please enter your name here