-1

I have a basic timer counting down right here. Starts at 5, goes to zero, no big deal. If I do not include the window.location into the if statement at the bottom to redirect the page after the timer reaches zero and the interval is cleared, there's two things that happen. If I add "window.location" before the clear interval statement, the interval will freeze at four seconds and stop counting down. If I add the window.location after the clear interval, the interval goes down to 4 and then automatically redirects before getting to zero. It's almost as if the code recognizes a "0" in between the 5 and 4 while counting down. Any advice?

<p> You will be redirected in <span id="countdowntimer">5 </span> Seconds</p>

<script type="text/javascript">
    var timeleft = 5;
    var downloadTimer = setInterval(function() {
        timeleft--;
        document.getElementById("countdowntimer").textContent = timeleft;
        if (timeleft <= 0)
            window.location.href = "testpage.html";
            clearInterval(downloadTimer);

    }, 1000);
</script>
Sébastien
  • 11,860
  • 11
  • 58
  • 78
maximus1127
  • 936
  • 11
  • 30
  • Aren't you clearing the interval after the if? – Fuczi Fuczi Dec 22 '17 at 21:09
  • yes, it was a brackets issue. i originally wrote the code in pieces and only cleared the interval after the if was satisfied. when i was ready to do the redirect, i just put the next line to execute but i forgot that a multi-line "if" needs brackets. I added the brackets and everything worked the way I wanted. I also switched the window.location to be after the "clear" statement – maximus1127 Dec 22 '17 at 21:10

1 Answers1

0

I figured it out, when i originally wrote the code, i didn't put brackets around the if conditions because it was a single line. I see now that i needed brackets around the multi-line if and it works fine now.

maximus1127
  • 936
  • 11
  • 30