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>