Michael Schwartz
Michael Schwartz

Reputation: 8415

SetTimeout and ClearTimeout (Doesn't clear at 0)

Maybe just sleep deprivation, but I can not understand what I'm doing wrong.

I'm calling a countDown function onLoad with setInterval.

Inside the countDown function I call clearTimeout when the number reaches 0 except it's called when it reaches 2.

What am I doing wrong?

Here's a snippet.

var interval, count = 5;

countDown()
interval = setInterval(countDown, 1000);

function countDown() {
  document.body.innerHTML = count
  count--

  if(count === 0) {
    clearInterval(interval)
    document.body.innerHTML = "Redirecting to ....."
  }
}

Upvotes: 0

Views: 65

Answers (3)

Riccardo
Riccardo

Reputation: 178

Just put the count-- after the if statement, and a return; at the end of the if statement if you want to block the execution after that.

var interval, count = 5;

countDown()
interval = setInterval(countDown, 1000);

function countDown() {
  document.body.innerHTML = count;
  

  if(count === 0) {
    clearInterval(interval);
    document.body.innerHTML = "Redirecting to .....";
    return;
  }
  count--
}

Upvotes: 1

Deep
Deep

Reputation: 9794

This is because you are decreasing the counter first and then evaluating, due to this 1 step is missed

var interval, count = 5;

countDown();
interval = setInterval(countDown, 1000);


function countDown() {
  

  if(count === 0) {
    clearInterval(interval)
    document.body.innerHTML = "Redirecting to ....."
  }
  else
  {
     document.body.innerHTML = count
     count--
  }
}

Upvotes: 1

Michal Toldy
Michal Toldy

Reputation: 175

function countDown() {
  document.body.innerHTML = count;
  if(count === 0) {
    clearInterval(interval)
    document.body.innerHTML = "Redirecting to .....";
  } else {
    count--;
  }
}

Upvotes: 1

Related Questions