我尝试在网页(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 秒调用一次。问题是当用户单击主页按钮时:
由于 anchor 标记和 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() 将阻止超链接的默认操作。
NOTE: You cannot continue a javascript function after a page reload.
关于javascript - 即使在 href 重定向之后如何使用 setTimeout 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50595913/