Nemoden
Nemoden

Reputation: 9056

Stop firing ajax requests

The issue is best explained by the code:

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);

So, what I want is to fire ajax requests each second to check if status of "something" changed. And if this something has changed properly, I want to stop checking on it. Basically, I'm asking how do I do it the best and most understood way.

What I did before is kind of ugly:

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]
};

So, yea, I've occupied global x here (this is my temporary storage). Now I can set my interval var to x:

setItem('myinterval', myinterval);

inside success function I can get this interval:

getIntem('myinterval');

and stop it:

clearInterval(getItem('myinterval'));

But this is really ugly, isn't it? What is the best better way of doing that?

Upvotes: 0

Views: 186

Answers (2)

nnnnnn
nnnnnn

Reputation: 150010

You're already saving a reference to the interval in myinterval, so what's wrong with:

clearInterval(myinterval);

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219920

Just use clearInterval(myinterval):

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

Upvotes: 2

Related Questions