[英]Stop firing ajax requests
代碼最好地解釋了這個問題:
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)
:
var myinterval = setInterval(function() {
$.ajax({
data: data
url: url,
success: function(data) {
if (data) {
clearInterval(myinterval);
}
}
});
}, 1000);
你已經在myinterval
保存了對間隔的myinterval
,所以有什么問題:
clearInterval(myinterval);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.