Countown Timer in Javascript
So , for creating a countdown timer we have to add one div or span for showing the timer. So you can add this in the html
<div class="jumbotron"> <h1>Jquery Countdown Timer</h1> </div> <div id="timer" style="font-size:30px"> 5:00 </div>
Now we have to add the javascript code for countdown timer. So you can add the following script in your page
setTimeout(startTimer, 1000); var ResetTimer = function () { document.getElementById('timer').innerHTML = "5 : 00"; } function startTimer() { var presentTime = document.getElementById('timer').innerHTML; var timeArray = presentTime.split(/[:]+/); var m = timeArray[0]; var s = checkSecond((timeArray[1] - 1)); if (s == 59) { m = m - 1 } if (m < 0) { return } document.getElementById('timer').innerHTML = m + ":" + s; if (parseInt(m) == 0 && parseInt(s) == 0) { ResetTimer(); } console.log(m) setTimeout(startTimer, 1000); } function checkSecond(sec) { if (sec < 10 && sec >= 0) { sec = "0" + sec }; // add zero in front of numbers < 10 if (sec < 0) { sec = "59" }; return sec; }
Here , you can see that we have added the timer for 5:00 minutes by default and then the countdown will work from that.When the timer will reach to zero we have down ResetTimer which we again set the value to initial value and timer will keep going.
You can check the output in the image
So this is how we can implement countdown timer in javascript.