倒计时器中的JavaScript重定向循环

I have a Javascript countdown timer in my page. Once the counter reachers zero, I want to redirect the user to another page. However, my page is entering a redirect loop and keeps redirecting to itself.

var count=20;

setInterval(timer, 1000);

function timer()
{
    if(count > 0)
    {
        count = count - 1;
    }
    else
        window.location = "<?= site_url('quiz/complete/' . $session->id); ?>";

    document.getElementById("timer").innerHTML = count;
}

You need to remove interval by clearInterval() function. Something like:

var count=20;

var interval = setInterval(timer, 1000);

function timer()
{
  if(count > 0)
  {
    count = count - 1;
  }
  else {
    clearInterval(interval);
    window.location = "<?= site_url('quiz/complete/' . $session->id); ?>";
  }
  document.getElementById("timer").innerHTML = count;

}

Here is another simple solution with pure JavaScript displaying the countdown timer using setInterval() function:

// Countdown timer for redirecting to another URL after several seconds
var seconds = 7; // seconds for HTML
var foo; // variable for clearInterval() function

function redirect() {
    document.location.href = 'http://bubencode.com';
}

function updateSecs() {
    document.getElementById("seconds").innerHTML = seconds;
    seconds--;
    if (seconds == -1) {
        clearInterval(foo);
        redirect();
    }
}

function countdownTimer() {
    foo = setInterval(function () {
        updateSecs()
    }, 1000);
}

countdownTimer();

See it working on JSFiddle here: http://jsfiddle.net/bubencode/dn6xc932/

I hope you will find it helpful.