Michael Schwartz Michael Schwartz - 4 months ago 18
Javascript Question

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 ....."
}
}




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