jQuery:如何停止定期运行的函数

时间:2013-02-23 09:51:44

标签: jquery ajax

我正在使用Google App Engine和Python开发系统。以下jQuery代码用于定期更新时间。以下HTML代码由jQuery Ajax插入content div:

HTML:

...
{{product.name}}: <br />
Bidding time is approaching: <div id="timeToBid{{product.randomNo}}">{{timeToBid}}</div>
...

$(document).ready(function() {
  function updateTime() {
    $.ajax({
      url: "/timeToBid?productId={{product.key.id}}",
      cache: false,
      success: function(returndata){
        $('#timeToBid{{product.randomNo}}').html(returndata);
      }
    });
    setTimeout(updateTime, 1000);
  }
  updateTime();
});

服务方计划:

class TimetoBid(webapp2.RequestHandler):
    def get(self):
        productId = self.request.get('productId')
        product = Product.get_by_id(productId)
        time = str(datetime.datetime.now() - product.bidTime)
        self.response.out.write(message)

但是,如果我单击页面中的其他按钮来更新content div,则updateTime()函数仍在运行,除非我刷新整个页面。另外,由于该功能不会停止,如果我多次进入该页面,问题会在一秒钟内运行几次。如果使用其他HTML代码更新content div,如何停止该功能?

2 个答案:

答案 0 :(得分:1)

setTimeout的结果分配给变量timer。更新内容div的代码可以调用clearTimeout(timer)

更新

另一个选项是updateTime()函数检查内容div是否已更改,并停止运行。

var oldContent;
function removeTimeToBid(str) {
    return str.replace(/<div id="timeToBid.*?<\/div>/, '');
}
function updateTime() {
   var newContent = removeTimeToBid($("#content").html());
   if (newContent != oldContent) { return; }
   $.ajax({
      url: "/timeToBid?productId={{product.key.id}}",
      cache: false,
      success: function(returndata){
        $('#timeToBid{{product.randomNo}}').html(returndata);
      }
   });
   setTimeout(updateTime, 1000);
}

function startUpdatingTime() {
    oldContent = removeTimeToBid($("#content").html());
    updateTime();
}

答案 1 :(得分:1)

您应该使用setInterval而不是setTimeout:

$(document).ready(function() {

  //Define variable to enable or disable the refresh function
  window.doRefresh = true;

  function updateTime() {

    //Execute AJAX request only if it is allowed
    if(!window.doRefresh)
        return;

    $.ajax({
      url: "/timeToBid?productId={{product.key.id}}",
      cache: false,
      success: function(returndata){
        $('#timeToBid{{product.randomNo}}').html(returndata);
      }
    });
  }

  //Permits to execute updateTime every seconds until clearInterval is called
  var intervalHandle = setInterval(updateTime, 1000);

  $('#myDiv').click(function(){
      //Stop definitely the interval code execution using
      clearInterval(intervalHandle);

      //Or use a variable to disable refreshing
      window.doRefresh = false;

      //Do some stuff...

      //Then enable refreshing like this
      window.doRefresh = true;
  });

});