On a download page, I would like to have it so that when the page loads, a 10 second timer automatically starts. On the page, I would like some text to say something like "You can begin your download in 10 seconds..." Then, after the time is up a download button appears for people to click on and start their download.
How can I do this, and what code do I use to include it into a page?
See: http://jsfiddle.net/rATW7/
It's backwards-compatible and not so secure, but 10 seconds isn't much to worry about anyways.
You can use setInterval()
to do this.
Note that make sure the countdownElement
has an existing text node, which can be any whitespace. If you can't guarantee that, just use innerHTML
or innerText/textContent
.
window.onload = function() {
var countdownElement = document.getElementById('countdown'),
downloadButton = document.getElementById('download'),
seconds = 10,
second = 0,
interval;
downloadButton.style.display = 'none';
interval = setInterval(function() {
countdownElement.firstChild.data = 'You can start your download in ' + (seconds - second) + ' seconds';
if (second >= seconds) {
downloadButton.style.display = 'block';
clearInterval(interval);
}
second++;
}, 1000);
}
jsFiddle.
Noone could ensure that your intervals are exact, especially if tab (or browser) is inactive (see e.g. this post), so it's better to rely on time difference instead of counter:
var sTime = new Date().getTime();
var countDown = 30;
function UpdateTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var seconds = countDown - Math.floor(diff / 1000);
//show seconds
}
UpdateTime();
var counter = setInterval(UpdateTime, 500);
The working fiddle
A modification of the Fiddle provided by Yuriy which does NOT use JQuery, and works with hours as well if the # of seconds are large enough.
<div id="countdowntimertxt" class="countdowntimer">00:00:00</div>
<script type="text/javascript">
var sTime = new Date().getTime();
var countDown = 3700; // Number of seconds to count down from.
function UpdateCountDownTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var timeStr = '';
var seconds = countDown - Math.floor(diff / 1000);
if (seconds >= 0) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor( (seconds-(hours*3600)) / 60);
seconds -= (hours*3600) + (minutes*60);
if( hours < 10 ){
timeStr = "0" + hours;
}else{
timeStr = hours;
}
if( minutes < 10 ){
timeStr = timeStr + ":0" + minutes;
}else{
timeStr = timeStr + ":" + minutes;
}
if( seconds < 10){
timeStr = timeStr + ":0" + seconds;
}else{
timeStr = timeStr + ":" + seconds;
}
document.getElementById("countdowntimertxt").innerHTML = timeStr;
}else{
document.getElementById("countdowntimertxt").style.display="none";
clearInterval(counter);
}
}
UpdateCountDownTime();
var counter = setInterval(UpdateCountDownTime, 500);
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With