【问题标题】:Stop jQuery ajax refresh after X secondsX 秒后停止 jQuery ajax 刷新
【发布时间】:2012-07-14 16:01:57
【问题描述】:

我使用 jQuery ajax 每 2 秒刷新一次 div。

如何在 60 秒后停止刷新(例如,如果用户处于非活动状态)?

setInterval(function() {
  $.ajax({
    url: "feeds.php",
    cache: false
  }).done(function( html ) {
  $('#feeds').replaceWith('<div id="feeds">'+html+'</div>');
   });
}, 2000);

谢谢!

【问题讨论】:

    标签: jquery ajax refresh setinterval


    【解决方案1】:

    将 setInterval 句柄分配给一个变量,您将在 60 秒后使用它来清除它。

    var interval = setInterval(function(){ ... }, 2000);
    
    // start a 60 second timer
    setTimeout(function(){ window.clearInterval(interval); }, 60000);
    

    【讨论】:

      【解决方案2】:

      没那么难。

      var myInterval = setInterval(function(){},2000);
      setTimeout(function() { clearInterval( myInterval ); }
      

      我不确定这是否有泄漏。

      【讨论】:

        【解决方案3】:
        //store the ajax call into a variable
        var chr =  $.ajax({ .....}
        
        //use setTimeout to invoke its abort() method after 1000 ms (1 second)
        setTimeout(function(){
          chr.abort()
        }, 1000);
        

        【讨论】:

        • 您能否解释一下为什么可以解决这个问题
        • setTimeout 函数将在 "1000"mseconds 后中止 ajax 调用,即 1 分钟或 60 秒的持续时间
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-05
        • 1970-01-01
        • 2015-03-01
        • 1970-01-01
        相关资源
        最近更新 更多