I am using the following javascript in the header to refresh the page
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
and in the body tag
<body onload="JavaScript:timedRefresh(5000);">
My question is how do I add a text showing the countdown to refresh the page
x seconds to refresh
I know this question has been already answered some time ago, but I was looking for similar code but with a longer (minutes) interval. It didn't come up in searches I did so this is what I came up with and thought I'd share:
Working fiddle
Javascript
function checklength(i) {
'use strict';
if (i < 10) {
i = "0" + i;
}
return i;
}
var minutes, seconds, count, counter, timer;
count = 601; //seconds
counter = setInterval(timer, 1000);
function timer() {
'use strict';
count = count - 1;
minutes = checklength(Math.floor(count / 60));
seconds = checklength(count - minutes * 60);
if (count < 0) {
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML = 'Next refresh in ' + minutes + ':' + seconds + ' ';
if (count === 0) {
location.reload();
}
}
HTML
<span id="timer"></span>
Does this suit your needs?
(function countdown(remaining) {
if(remaining <= 0)
location.reload(true);
document.getElementById('countdown').innerHTML = remaining;
setTimeout(function(){ countdown(remaining - 1); }, 1000);
})(5); // 5 seconds
JSFiddle
Working fiddle
function timedRefresh(timeoutPeriod) {
var timer = setInterval(function() {
if (timeoutPeriod > 0) {
timeoutPeriod -= 1;
document.body.innerHTML = timeoutPeriod + ".." + "<br />";
// or
document.getElementById("countdown").innerHTML = timeoutPeriod + ".." + "<br />";
} else {
clearInterval(timer);
window.location.href = window.location.href;
};
}, 1000);
};
timedRefresh(10);
I don't really see why you would use setTimeout
for this purpose.
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