Javascript 每 30 秒自动刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32913226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto refresh page every 30 seconds
提问by Mary
I have a JSP page which has to display the status of various jobs that are running. Some of these jobs take time, so it takes a while for their status to change from processing to complete.
我有一个 JSP 页面,它必须显示正在运行的各种作业的状态。其中一些作业需要时间,因此它们的状态从处理变为完成需要一段时间。
Is it a good idea to have a javascript function that would refresh the page every 30 seconds or so? Are there any ramifications for having a script that is constantly refreshing a page?
拥有一个每隔 30 秒左右刷新一次页面的 javascript 函数是个好主意吗?拥有不断刷新页面的脚本是否有任何后果?
The other option is to have a refresh button which on click would refresh the page.
另一种选择是有一个刷新按钮,点击它会刷新页面。
回答by jeerbl
There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta
tag in your head
tag.
对此有多种解决方案。如果您希望刷新页面,您实际上不需要 JavaScript,如果您在meta
标签中添加此标签,浏览器可以为您完成head
。
<meta http-equiv="refresh" content="30"/>
The browser will then refresh the page every 30 seconds.
然后浏览器将每 30 秒刷新一次页面。
If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with location.reload()
(docs) inside a setTimeout()
:
如果你真的想用 JavaScript 来做,那么你可以每 30 秒刷新一次页面,在 a 中使用location.reload()
( docs) setTimeout()
:
setTimeout(function() {
location.reload();
}, 30000);
Otherwise, if you don't need to refresh the whole page but only a part of it, I guess an Ajax call would be the most efficient way.
否则,如果您不需要刷新整个页面而只需要刷新其中的一部分,我猜 Ajax 调用将是最有效的方式。
回答by 404
Just a simple line of code in the head section can refresh the page
只需在head部分简单的一行代码就可以刷新页面
<meta http-equiv="refresh" content="30">
<meta http-equiv="refresh" content="30">
although its not a javascript function, its the simplest way to accomplish the above task hopefully.
虽然它不是一个 javascript 函数,但它是有希望地完成上述任务的最简单方法。
回答by ishandutta2007
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
使用setInterval
代替setTimeout
。尽管在这种情况下,两者都可以,但setTimeout
本质上只会setInterval
无限期地触发一次。
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
回答by Patrik Fr?hler
If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.
如果你想刷新页面你可以这样使用,但刷新页面通常不是最好的方法,最好尝试只更新你需要更新的内容。
javascript:
javascript:
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 30000);
</script>