Create a simple 10 second countdown
JavaScript has built in to it a function called setInterval
, which takes two arguments - a function, callback
and an integer, timeout
. When called, setInterval
will call the function you give it every timeout
milliseconds.
For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.
function makeAlert(){
alert("Popup window!");
};
setInterval(makeAlert, 500);
However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.
setInterval(function(){ alert("Popup window!"); }, 500);
Once setInterval
is called, it will run until you call clearInterval
on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.
var timeleft = 10;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
}
document.getElementById("progressBar").value = 10 - timeleft;
timeleft -= 1;
}, 1000);
<progress value="0" max="10" id="progressBar"></progress>
Alternatively, this will create a text countdown.
var timeleft = 10;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Finished";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
<div id="countdown"></div>
This does it in text.
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>
<script type="text/javascript">
var timeleft = 10;
var downloadTimer = setInterval(function(){
timeleft--;
document.getElementById("countdowntimer").textContent = timeleft;
if(timeleft <= 0)
clearInterval(downloadTimer);
},1000);
</script>
A solution using Promises, includes both progress bar & text countdown.
ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));
function ProgressCountdown(timeleft, bar, text) {
return new Promise((resolve, reject) => {
var countdownTimer = setInterval(() => {
timeleft--;
document.getElementById(bar).value = timeleft;
document.getElementById(text).textContent = timeleft;
if (timeleft <= 0) {
clearInterval(countdownTimer);
resolve(true);
}
}, 1000);
});
}
<div class="row begin-countdown">
<div class="col-md-12 text-center">
<progress value="10" max="10" id="pageBeginCountdown"></progress>
<p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>
</div>
</div>