How to Create Timer Using JavaScript
The following example shows, how to create Timer using JavaScript.
Demo
Example
<html> <head> <style> @font-face{ font-family:'digital-font'; src: url('digital-7.ttf'); } .timer input{ font-family:digital-font; font-size:25px; text-align:right; width:40px; padding:5px; } </style> </head> <body> <div class='timer'> <input type='text' value='00' id='hour'> h: <input type='text' value='05' id='minute'> m: <input type='text' value='00' id='second'> s </div> <br> <input type='button' value='Start' id='btn'> <input type='button' value='Reset' id='reset'> <script> var interval; document.querySelector("#btn").onclick=function(){ var btn=document.querySelector("#btn"); if(btn.value=='Start'){ interval=setInterval(timer,1000); btn.value='Stop'; document.querySelector("#hour").disabled=true; document.querySelector("#minute").disabled=true; document.querySelector("#second").disabled=true; }else{ clearInterval(interval); btn.value='Start'; document.querySelector("#hour").disabled=false; document.querySelector("#minute").disabled=false; document.querySelector("#second").disabled=false; } } document.querySelector("#reset").onclick=function(){ clearInterval(interval); document.querySelector("#hour").value="00"; document.querySelector("#minute").value="05"; document.querySelector("#second").value="00"; document.querySelector("#hour").disabled=false; document.querySelector("#minute").disabled=false; document.querySelector("#second").disabled=false; } function timer(){ var hour=document.querySelector("#hour"); var minute=document.querySelector("#minute"); var second=document.querySelector("#second"); h=Number(hour.value); m=Number(minute.value); s=Number(second.value); s--; if(s<0&&m!=0){ s=59; m--; } if(m<0&&s!=0){ m=59; h--; } if(m==0&&s==0){ clearInterval(interval); } hour.value=formatTime(h); minute.value=formatTime(m); second.value=formatTime(s); } function formatTime(x){ if(x<10){ return "0"+x; } return x; } </script> </body> </html>Try it Yourself