Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 停止激发ajax请求_Javascript_Jquery_Javascript Events - Fatal编程技术网

Javascript 停止激发ajax请求

Javascript 停止激发ajax请求,javascript,jquery,javascript-events,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 re

以下代码最好地解释了这个问题:

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'));
但这真的很难看,不是吗?
最好的方法是什么?

只需使用
clearInterval(myinterval)


您已经在
myinterval
中保存了对时间间隔的引用,那么:

clearInterval(myinterval);
设置
var x=$.ajax(…”;
然后在需要时设置x.abort()。
clearInterval(myinterval);