Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript refresh + countdown text

Tags:

javascript

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

like image 302
David Garcia Avatar asked May 13 '13 23:05

David Garcia


3 Answers

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>
like image 97
cassidymack Avatar answered Sep 29 '22 08:09

cassidymack


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

like image 21
Paul Avatar answered Nov 18 '22 16:11

Paul


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.

like image 8
flavian Avatar answered Nov 18 '22 15:11

flavian