If you are into web development and trying to build an application where you need to show countdown timer. For example session expiry countdown. Here is the code written in pure JavaScript which will show countdown timer in in hours, minutes and seconds. You need to pass input in minutes and seconds.
It will convert minutes into proper format. Like if it is above 60 it will be converted as hour and rest in minutes. Most of the time seconds values that we pass is 0.
CODE for count down timer using JavaScript
function countdown( elementName, minutes, seconds ) { var element, endTime, hours, mins, msLeft, time; function twoDigits( n ) { return (n <= 9 ? "0" + n : n); } function updateTimer() { msLeft = endTime - (+new Date); if ( msLeft < 1000 ) { element.innerHTML = "countdown's over!"; } else { time = new Date( msLeft ); hours = time.getUTCHours(); mins = time.getUTCMinutes(); element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() ); setTimeout( updateTimer, time.getUTCMilliseconds() + 500 ); } } element = document.getElementById( elementName ); endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500; updateTimer(); } countdown( "countdown", 5, 0 );
You can just use this JavaScript code and add below line in html code
<div id="countdown"></div>
Please share if you have another idea to do it in easier way.