Home > Mobile >  Why clearinterval() does not stops the setInterval() in JS?
Why clearinterval() does not stops the setInterval() in JS?

Time:11-03

I need to start the setInterval When the particular id is 2 and to clear the Interval using clearInterval.

When I click on the button, the value in the button should be 0,1,2,3,0,1,2.... When the value is 2, it should display Date.now().


<button id="b1">0</button>
<button id="b2">0</button>
<button id="b3">0</button>

$("button").click(function () {
  buttonVal(this);
});

var v = [];

function buttonVal(ele) {
  v[ele.id] =
    typeof v[ele.id] === "undefined" ? 0 : v[ele.id] === 3 ? 0 : v[ele.id]   1;
  switch (v[ele.id]) {
    case 0:
      break;
    case 1:
      document.getElementById(ele.id).innerHTML = v[ele.id];
      break;

    case 2:
      document.getElementById(ele.id).innerHTML = v[ele.id];
      break;

    case 3:
      document.getElementById(ele.id).innerHTML = v[ele.id];
      break;

    default:
      document.getElementById(ele.id).innerHTML = 6;
      break;
  }
 if(v[ele.id] == 2) {
   
   var refreshId = setInterval(function(){
     v[ele.id] = {'refreshId': refreshId};
     document.getElementById(ele.id).innerHTML = Date.now();
    }, 2000);
   }
  else {
    clearInterval(refreshId);
  }
}

The problem is clearInterval() is not working, When the button value is 2, it starts the setInterval()but it doesn't stops when the value is not 2. It just continues to run for all the button Values.

The button value runs like the below after clicking them 0,1,2,3, object1, object11, object111. Not sure, why the order is like the above.

Could anyone please help to stop the timer for the values other than 2.

Many thanks.

CodePudding user response:

You are defining var refreshId inside the if block, and trying to clear it in else, so the scope isn't the same. Your refreshId is a local variable.

Try defining it first outside the if block, or rather outside of the function itself.

var refreshId = null;

if(v[ele.id] == 2) {
 refreshId = setInterval(...)
 ...
else {
 clearInterval(refreshId);
}


CodePudding user response:

When running a function all variables get redeclared again, this means when you say: var intervalId = interval(...). You create a new variable instead of saving it for later.

To solve this problem save the interval globally like shown below:

let interval;

function buttonVal(ele) {
 // code...
 
 if(v[ele.id] == 2) {
   interval = setInterval(function(){
     v[ele.id] = {'refreshId': refreshId};
     document.getElementById(ele.id).innerHTML = Date.now();
    }, 2000);
   }
  else {
    if (interval) {
      clearInterval(refreshId);
    }
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related