Javascript refresh + countdown text
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>
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.
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
You'd have to run the timeout every second, update the DOM and only reload when you need to:
<script type="text/JavaScript">
<!--
var i = 5000;
function timedRefresh(timeoutPeriod) {
i = timeoutPeriod;
updateDom();
}
// -->
function updateDom(){
body.innerHTML = i;
i--;
if (i==0){
location.reload(true);
}
else{
setTimeout(updateDom, 1000);
}
}
// -->
</script>