How to create a timer in javascript

{0 Comments}

Timer is kind of event which automatically execute after a time of specified number of millisecond. In order to write a timer in JavaScript we can do this as follows,

First have a label whose id is lbltext then we have two button one is start timer which call test function. And other is stop timer which call a stop count function. Know in the test function which definitely starts the timer.  In this function we are incrementing the counter.  Which is declared before as a variable In this function after every function, we will increment the value/data of the label. And set the value as the inner html of the given label. We will call JavaScript set time out function which accepts two parameters first accept function which is to be called and second parameter is after how many millisecond it is called.  So this is a recursive function that mean, this function will call itself.  So after every second text function is called. 

 Javascript |  copy code |? 
01
<script type="text/javascript" >
02
    var count=0;
03
    function testfunction()
04
    {
05
    count++;
06
    document.getElementById("lbltext").innerHTML=count;
07
    t=setTimeout("testfunction()",1000);
08
    } 
09
 
10
    function stop()
11
    {
12
    clearTimeout(t);
13
    }
14
 
15
 
16
    </script>

and aspx code

 HTML |  copy code |? 
1
 <input id="Button2" type="button" onclick="testfunction()" value="start" />
2
        <input id="Button1" type="button" onclick="stop()" value="stop" />
3
 
4
        <asp:Label ID="lbltext" runat="server" Text="Label">0</asp:Label>

Leave a Comment

Your email address will not be published.