Create a seconds countdown in 6 lines of JavaScript
TIL how to create a seconds countdown in just 6 lines of JavaScript.
The HTML:
<!-- Replace 10 with the seconds you want to count down from -->
<span id="countdown">10</span>
The JavaScript:
var seconds = document.getElementById("countdown").textContent;
var countdown = setInterval(function() {
seconds--;
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
See above code in action on JSFiddle.
Running into a small challenge
I wanted to display xx seconds
, but then I realised I must use second
if 1
and seconds
otherwise. I solved it this way:
The HTML:
<!-- Replace 10 with the seconds you want to count down from -->
<span id="countdown">10</span> second<span id="plural">s</span>
The JavaScript:
var seconds = document.getElementById("countdown").textContent;
var countdown = setInterval(function(){
seconds--;
(seconds == 1) ? document.getElementById("plural").textContent = "" : document.getElementById("plural").textContent = "s";
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
},1000);
See above code in action on JSFiddle.
Where do I use this?
I use this at tonnygaric.com/github and tonnygaric.com/linkedin. On these pages I redirect users to, respectively, my GitHub and LinkedIn profile. I want to explicitly show users that they will be redirected in xx seconds
.
I would love to shorten this code. If you know how, please share! 🙂
UPDATE 2017-11-21: Joris Zwart shared a seconds countdown in 5 lines of JavaScript in the comments, see JSFiddle.
The HTML:
<span id="countdown"></span>
The JavaScript:
var seconds = 10, $seconds = document.querySelector('#countdown');
(function countdown() {
$seconds.textContent = seconds + ' second' + (seconds == 1 ? '' : 's')
if(seconds --> 0) setTimeout(countdown, 1000)
})();