2013-05-13 87 views
7

我使用下面的JavaScript在頭刷新頁面的Javascript刷新+倒計時文本

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

,並在body標籤

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

我的問題是如何添加一個文本顯示刷新頁面的倒計時

x秒刷新

+0

你試過了什麼?搜索網絡的「JavaScript倒計時」,有這麼多的例子... – Bergi 2013-05-13 23:06:34

回答

17

這是su它是你的需求嗎?

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

JSFiddle

+0

這似乎工作在小提琴,但是當我將它添加到我的網頁它甚至不顯示文本也不會刷新, – 2013-05-13 23:17:11

+0

http://uelhub.com/fingerprinting /這是 – 2013-05-13 23:17:27

+0

我試過了頭部和身體 – 2013-05-13 23:18:47

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> 
6

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

我真的不明白爲什麼你會爲此使用setTimeout

+0

感謝,但它可以顯示其下只有一條線:P – 2013-05-13 23:21:02

+0

差不多的工作,但同時也開始倒計時,它隱藏在頁面的內容,看看HTTP:/ /uelhub.com/fingerprinting/ – 2013-05-13 23:27:55

+0

這似乎是一個比繼續重複加載更好的解決方案。 – 2015-08-24 17:42:35

5

我知道這個問題已經有一段時間了,但我一直在尋找類似的代碼,但間隔時間更長(分鐘)。它沒有拿出在搜索我這樣做了,這是我想出了,以爲我會分享:

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>