2011-12-27 103 views
0

問題最好由代碼解釋:停止射擊Ajax請求

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這裏(這是我的臨時存儲)。現在,我可以把我的時間間隔varx

setItem('myinterval', myinterval); 

內成功的功能,我可以得到這個區間:

getIntem('myinterval'); 

並停止它:

clearInterval(getItem('myinterval')); 

但這實在是太醜了,不是嗎? 什麼是最好的方法呢?

+0

集'變種X = $阿賈克斯(.. 。';'然後當你需要它時x.abort()。 – 2011-12-27 04:48:08

回答

2

只需使用clearInterval(myinterval)

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

你已經在myinterval保存到區間的引用,所以這有什麼錯:

clearInterval(myinterval);