9

ページを更新するためにヘッダーで次のJavaScriptを使用しています

    <script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
    setTimeout("location.reload(true);",timeoutPeriod);
}
//   -->
</script>

そしてボディタグで

<body onload="JavaScript:timedRefresh(5000);">

私の質問は、カウントダウンを示すテキストを追加してページを更新する方法です

リフレッシュするのに x 秒

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 に答える