AKAust
AKAust

Reputation: 113

Javascript clearInterval is not having an effect?

I am trying to do a simple redirect after x seconds on a page with a countdown timer. Every time I call the function I want the timer to be reset, however when i call it a second or third time the timer seems to have 3 different countdowns. Can anyone see why this is?

function delayRedirect(){
  document.getElementById('countDown').innerHTML = 'Session Timeout In: <span id="countTimer"></span> seconds....';
  clearInterval(sessionTimer);
  var sessionTimer = null;
  var timeleft = 60;
  var sessionTimer = setInterval(function(){
     timeleft--;
     document.getElementById('countTimer').innerHTML = timeleft;
     if(timeleft <= 0)
         clearInterval(sessionTimer);
         returnToLogin();
     },1000);
}

Upvotes: 1

Views: 95

Answers (2)

user5734311
user5734311

Reputation:

I feel like all the answers only address the Y part, not the X part, given that this is clearly an XY problem. While the solution is to use a variable that isn't local to the function, solving the actual problem doesn't require clearing anything. One can simply use an interval to tick down, and reset the count to delay the redirect:

var timeleft = 60;

setInterval(function() {
  if (--timeleft === 0) returnToLogin();
  countTimer.innerHTML = timeleft;
}, 1000);

delay.onclick = function() {
  timeleft = 60;
}

function returnToLogin() {
  console.log("returning to login");
}
<p>Session Timeout In: <span id="countTimer">60</span> seconds....</p>
<button id="delay">Delay</button>

Upvotes: 1

kockburn
kockburn

Reputation: 17616

Put the sessionTimer globally. What you currently do is re-declare sessionTimer every time you enter delayRedirect.

Working example:

const but = document.getElementById("but");
but.addEventListener("click", delayRedirect);

//define it globally
var sessionTimer = -1;

function delayRedirect() {
  //clear it if it previously exists
  clearInterval(sessionTimer);
  sessionTimer = setInterval(function() {
    console.log("sessionTimer " + sessionTimer);
  }, 1000);
}
<button id="but">Run</button>

Upvotes: 1

Related Questions