9

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

4

5 回答 5

21

这符合您的需求吗?

(function countdown(remaining) {
    if(remaining <= 0)
        location.reload(true);
    document.getElementById('countdown').innerHTML = remaining;
    setTimeout(function(){ countdown(remaining - 1); }, 1000);
})(5); // 5 seconds

JSFiddle

于 2013-05-13T23:08:50.063 回答
8

工作小提琴

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);

我真的不明白你为什么要setTimeout用于这个目的。

于 2013-05-13T23:14:39.820 回答
8

我知道这个问题已经在一段时间前得到了回答,但我一直在寻找类似的代码,但间隔更长(分钟)。它没有出现在我所做的搜索中,所以这就是我想出的,并认为我会分享:

工作小提琴

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>
于 2013-09-11T16:25:02.443 回答
1

您必须每秒运行一次超时,更新 DOM 并仅在需要时重新加载:

 <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>
于 2013-05-13T23:08:57.283 回答
0

因为我的页面没有在一秒钟内刷新(在开发中),所以我稍微修改了 Paul 的答案:

(function countdown(remaining) {
    if(remaining === 0)
        location.reload(true);
    if(remaining > 0)
      document.getElementById('countdown').innerHTML = remaining;
      setTimeout(function(){ countdown(remaining - 1); }, 1000);
})(30); // 30 seconds

发生的事情是计数器每秒都在发出新的 GET,而页面从未加载过更改。额外的测试解决了这个问题。

于 2020-05-20T07:19:51.030 回答