dsuma
dsuma

Reputation: 1010

clearInterval Logic problems

I am having an issue with clearing an interval in the logic I am using. the clearInterval is not working as I would assume it would. any suggestions on how to incorporate my logiuc below so clearInterval would work? The toggleInterval gets called on change.

var interval;
function toggleInterval(setting, interval) {
      switch (setting) {
          case SET_INTERVAL: 
            interval = setInterval(function() {
                poll(true, interval);
            }, 5000);  
            break;
        case CLEAR_INTERVAL:
            clearInterval(interval);
            break;    
    }   
}   


function poll(polled, interval) {
    if (!polled) {
        $pollPromise = $.ajax({
            url: '/stuff/',
        }); 

        $pollPromise.done(success);
        function success(data) {
            if (data.success) {
                // .... DO stuff
                toggleInterval(CLEAR_INTERVAL, interval);
            }   
            return;
        } 
    }   
}   

Upvotes: 0

Views: 50

Answers (2)

Paul Roub
Paul Roub

Reputation: 36438

You're not really storing the setInterval() value anywhere.

Your interval parameter (a local variable) hides the var interval; declaration, so once the toggleInterval() exits, that value is lost. Return the value so it can be used by the caller to set the global variable:

var interval;

function toggleInterval(setting, interval) {
      switch (setting) {
          case SET_INTERVAL: 
            return setInterval(function() {
                poll(true, interval);
            }, 5000);  

        case CLEAR_INTERVAL:
            clearInterval(interval);
            break;    
    }   
}       

function poll(polled, interval) {
    if (!polled) {
        $pollPromise = $.ajax({
            url: '/stuff/',
        }); 

        $pollPromise.done(success);
        function success(data) {
            if (data.success) {
                // .... DO stuff
                toggleInterval(CLEAR_INTERVAL, interval);
                interval = null;
            }   
            return;
        } 
    }   
}   

// elsewhere:
interval = toggleInterval(SET_INTERVAL);

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

When ever set interval is called, you are creating a new interval to poll. You need to clear the interval first and then create a new interval.

case SET_INTERVAL: 
            interval = setInterval(function() {
                poll(true, interval);
            }, 5000);  
            break;

should be changed to

case SET_INTERVAL: 
            clearInterval(interval);   <-----
            interval = setInterval(function() {
                poll(true, interval);
            }, 5000);  
            break;

Upvotes: 1

Related Questions