[英]How to loop with setTimeout even after a href redirect?
我尝试在这样的网页(Facebook)上运行循环方法:
function loopRefresh () {
console.log("loop refresh method call");
if (shallRefresh){
setTimeout(function(){
loopRefresh()
//Do something here
}, 5000);
} else {
setTimeout(function(){
loopRefresh()
//Do something different here
}, 5000);
}
}
到目前为止,一切顺利,并且每5秒调用一次该方法。 问题是当用户单击主页按钮时:
即使该页面未引用新页面,该页面也会因定位标记和href而重新加载。 这打破了循环。
我已经将此功能作为onclick事件添加到“主页”按钮:
function homeRefresh() {
shallRefresh = true;
//setTimeout(function(){
// Do the same thing here as in the true case in the loopRefresh method
// }, 2000);
}
我最初只是想在此处进行setTimeout调用,以便在用户单击按钮后执行回调函数,而无需使用loopRefresh方法。 但是我认为我可以通过传递变量来解决问题,这也不起作用。
在函数启动时使用event.preventDefault() 。 喜欢,
function homeRefresh() {
event.preventDefault(); // here..
shallRefresh = true;
//setTimeout(function(){
// Do the same thing here as in the true case in the loopRefresh method
// }, 2000);
}
event.preventDefault()将阻止超链接的默认操作。
注意:重新加载页面后,您将无法继续javascript功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.