停止触发ajax请求

时间:2011-12-27 04:46:09

标签: javascript jquery javascript-events

问题最好由代码解释:

var myinterval = setInterval(function() {
    $.ajax({
        data: data
        url: url,
        success: function(data) {
            if (data) { /* I want to clear current interval */ }
            else { /* let it firing ajax requests further */ }
        }
    });
}, 1000);

所以,我想要的是每秒触发ajax请求以检查“某事”的状态是否发生了变化。如果这件事情发生了变化,我想停止检查。基本上,我问我如何以最好和最了解的方式做到这一点。

我以前做过的事情有点难看:

window.x = {
  'debug' : document.location.host.indexOf('.ru') != document.location.host.length - 3
  };
var setItem = function(i,v) {
  if (window.x['debug'] && typeof window.x[i] != 'undefined' && typeof console != 'undefined' && window.x[i] != v)
    console.log('Value of item ' + i + ' has changed from ' + window.x[i] + ' to ' + v)
  window.x[i] = v
};
var getItem = function(i) {
  if (window.x['debug'] && typeof window.x[i] == 'undefined' && typeof console != 'undefined')
    console.warn('Value of item ' + i + ' is undefined (maybe was not set?)')
  return window.x[i]
};

所以,是的,我在这里占据了全球x(这是我的临时存储空间)。现在,我可以将时间间隔var设置为x

setItem('myinterval', myinterval);

内部成功功能我可以得到这个间隔:

getIntem('myinterval');

并停止它:

clearInterval(getItem('myinterval'));

但这真的很难看,不是吗? 什么是最好的更好的方法呢?

2 个答案:

答案 0 :(得分:2)

只需使用clearInterval(myinterval)

var myinterval = setInterval(function() {
    $.ajax({
        data: data
        url: url,
        success: function(data) {
            if (data) {
                clearInterval(myinterval);
            }
        }
    });
}, 1000);

答案 1 :(得分:0)

您已经在myinterval中保存了对时间间隔的引用,所以出了什么问题:

clearInterval(myinterval);
相关问题