[英]Button to refresh page every second/minute etc?
我想要一个按钮,单击该按钮将在指定的时间后刷新当前页面。
我目前有:
<script type="text/javascript">
setTimeout(function reload(){
location = ''
},1000)
</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);
}
这应该可以解决问题
<script type="text/javascript">
function reload(){
setTimeout(function(){location.reload()}, 3000);
}
</script>
<button onclick="reload()">Reload</button>
你写的是
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;
}
而你说你希望它继续运行。 这将需要cookie或localstorage。
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();
}
您需要将整个事物包装在另一个函数中并从按钮单击调用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.