Menu ▼



Posted By :
avatarmrkraju
Total Views : 5252

JavaScript Timer Control By Using setTimeout function

We can create timer control by using JavaScript. setTimeout is the JavaScript in built function, which we can use to execute JavaScript Code after a specific time elapsed. The below timer control is generated by using JavaScript setTimeout function.
Below is the source code to generate the timer using JavaScript.

           


<html>

<head>

    <script language="javascript">

        var dt = null;

        setTimeout(setTime, 100);

        function setTime() {

            if (dt == null)

                dt = new Date();

            var totalseconds = parseInt(((new Date()) - dt) / 1000, 10);

            var hh = parseInt(totalseconds / (60 * 60), 10);

            var mm = parseInt((totalseconds - (hh * 60 * 60)) / 60, 10);

            var ss = parseInt(totalseconds - (hh * 60 * 60) - (mm * 60), 10);

            document.getElementsByName("txttimer")[0].value = (hh > 9 ? hh : ('0' + hh)) + ":" + (mm > 9 ? mm : ('0' + mm)) + ":" + (ss > 9 ? ss : ('0' + ss));

            setTimeout(setTime, 1000);

        }

    </script>

</head>

<body>

    <div style="margin: auto; text-align: center;">

        <input type="text" readonly="readonly" name="txttimer" style="text-align: center;

            color: Blue; font-weight: bold; border: solid 1px red; padding: 5px; width: 100px;

            height: 27px; margin: auto;" />

    </div>

</body>

</html>






comments powered by Disqus


Search dotnetlearners.com