# Count down ###### tags: `javascript` --- ## How to write a countdown timer in JavaScript?[🔗](https://stackoverflow.com/questions/20618355/how-to-write-a-countdown-timer-in-javascript) ### with Vanilla JavaScript ```html <body> <div>Registration closes in <span id="time">05:00</span> minutes!</div> </body> ``` ```javascript function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { timer = duration; } }, 1000); } window.onload = function () { var fiveMinutes = 60 * 5, display = document.querySelector('#time'); startTimer(fiveMinutes, display); }; ``` ### with jQuery ```html <body> <div>Registration closes in <span id="time"></span> minutes!</div> </body> ``` ```javascript function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.text(minutes + ":" + seconds); if (--timer < 0) { timer = duration; } }, 1000); } jQuery(function ($) { var fiveMinutes = 60 * 5, display = $('#time'); startTimer(fiveMinutes, display); }); ``` ### more accurate timer ```javascript function startTimer(duration, display) { var start = Date.now(), diff, minutes, seconds; function timer() { // get the number of seconds that have elapsed since // startTimer() was called diff = duration - (((Date.now() - start) / 1000) | 0); // does the same job as parseInt truncates the float minutes = (diff / 60) | 0; seconds = (diff % 60) | 0; minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (diff <= 0) { // add one second so that the count down starts at the full duration // example 05:00 not 04:59 start = Date.now() + 1000; } }; // we don't want to wait a full second before the timer starts timer(); setInterval(timer, 1000); } window.onload = function () { var fiveMinutes = 60 * 5, display = document.querySelector('#time'); startTimer(fiveMinutes, display); }; ```