javascript - 即使在 href 重定向之后如何使用 setTimeout 循环?

标签 javascript facebook settimeout

我尝试在网页(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 秒调用一次。问题是当用户单击主页按钮时: Facebook Home Button Code

由于 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/

相关文章:

javascript - 设置 zIndex KmlLayer 的解决方法

javascript - 为什么悬停不能处理 jqgrid 中的彩色行

javascript - 如何在 Google Chrome 扩展中构建 HUD?

javascript - 我如何在 php codeigniter 上运行 ajax

javascript - Python 到 javascript 通信

javascript - 使用 facebook javascript sdk 访问登录用户的电子邮件

java - 如果已经创建了用户,则正确的代码位置检查 Firebase?

javascript - 如何在 javascript 中使用 setTimeout 考虑延迟

使用电话号码的Android facebook登录返回空用户名

javascript - 如何在 javascript 或 jquery 中刷新或重新加载超时的页面