按钮刷新页面每秒/分钟等?
我想要一个按钮,点击后将在指定的时间后刷新当前页面。按钮刷新页面每秒/分钟等?
我目前有:
<script type="text/javascript">
setTimeout(function reload(){
location = ''
},1000)
</script>
<button onclick="reload()">Reload</button>
然而,这只是重新加载,甚至无需点击按钮的页面。我想要按钮来执行脚本,并且还有一个按钮来停止页面重新加载。
这应该是很简单,但我无法弄清楚:(
******编辑**********
我还像脚本单击该按钮后,在一个无限循环中运行。
这应该做的伎俩
<script type="text/javascript">
function reload(){
setTimeout(function(){location.reload()}, 3000);
}
</script>
<button onclick="reload()">Reload</button>
你setTimeout
被称为在页面加载,你需要把它放在reload()
函数内部:
function reload() {
setTimeout(function() {
window.location.reload();
}, 1000);
}
为了使定时器运行每x秒和重装只有一个这样的网页的一部分,您将需要使用setInterval
和AJAX请求,东西:
var timer;
function reload() {
timer = setInterval(function() {
$.post('foo.html', function(data) {
$('#bar').html(data);
});
}, 1000);
}
function clear() {
clearInterval(timer);
}
OP也想清除超时 – Turnip 2014-09-19 13:53:11
谢谢Rory,这对我所问的问题工作得很好。不过,我确实忘了提及,我希望脚本在点击按钮后在无限循环中运行,对不起。 – 2014-09-19 13:54:41
@LukeJennings当你重新加载页面时,这将不可能,所以它将被设置回初始状态。要做你需要的东西,你需要使用AJAX每X秒刷新页面的一部分。 – 2014-09-19 13:55:49
你需要用另一种功能,整个事情并调用从按钮单击
你写的是什么
window.setTimeout("location = ''"; ,1000);
您是在1秒后执行此功能。你需要在函数内定义setTimeout。还有一个内置的方法来重新加载页面。打电话,而不是将位置设置为空白字符串。
function reload() {
setTimeout(function() {
window.location.reload(true);
},1000);
}
现在要取消超时,您需要使用clearTimeout(timeoutId)
;您可以从setTimeout在调用它时返回的整数中获取timeoutId。
var timer = null;
function reload() {
timer = window.setTimeout(function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
}
你说你想让它继续运行。这将需要cookies或本地存储。
var timer = null;
function reload() {
localStorage.reload = true; //set localstorage so we know to fire it off again
timer = window.setTimeout(function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
localStorage.removeItem("reload"); //remove the key in localstorage
}
if (localstorage.reload) { //check localstorage to see if key is set
reload();
}
将你的“setTimeout”放入函数中。并从按钮调用该功能。 – 2014-09-19 13:52:24