ClearInterval not clearing SetInterval

Ankur Garg picture Ankur Garg · Mar 14, 2013 · Viewed 9k times · Source

When we call clearInterval with the value returned by SetInterval does it make that value null or undefined.

I am calling clearInterval to clear setInterval but apparently value of setInterval remains same and does not change even after calling clearInterval . Is t suppposed to be null or undefined ? Here is my code snippet

var setIntervalId; // declared in global scope
//lined of code

function autorefresh() {
  if (statesCount > 0) {
    setIntervalId = setInterval(function() {
        //lines of code
        // calling some handler
    }, 30000);
  }

  if (statesCount === 0) {
    clearInterval(setIntervalId);
  }
}

As you can see I am calling my setInterval function every 30 seconds , when called for the first time assigns some value to setIntervalId , but even after calling clearInterval the value persists. Should it become null or undefined after calling clearInterval?If it should be null or undefined what should I do here.I have defined setIntervalId in global scope.

Answer

JaredPar picture JaredPar · Mar 14, 2013

The function clearInterval will not clear the value that is passed into it. If you want to clear it you must do that yourself

clearInterval(setIntervalId);
setIntervalId = undefined;

Note that it doesn't appear like you are properly guarding the initial call to setInterval. This could result in the call being made multiple times and hence you having multiple interval setups. I think you should augment your initial if block to the following

if (statesCount > 0 && typeof(setIntervalId) === 'undefined') { 
  ...
}