0

I have been working on a count down for most of today, and now I am stuck on looping. Without the for loop everything works fine the count down hits 0 and reloads, but with the for loop it doesn't count down properly and skips numbers. What I would like to accomplished here is to have the timer count down completely and after 3 complete count downs it will stop completely. What am I doing wrong here?

var number = 25;
var i;

function countdown() {
    $('#display').html("Redirecting in " + number + " second(s).");
    for (i = 0; i < 3; ++i) {
        number--;
        if (number < 0) {
            window.location.reload();
            number = 0;
        }
    }
    setTimeout(countdown, 1000);
}

$(document).ready(function() {
    countdown();
});
4
  • If it works without the loop, why are you still using it? Commented Jan 14, 2012 at 14:18
  • You decrement number four times in the loop--of course it skips numbers. You also reload, which will start the whole process over again--unless you store the "total" count somewhere persistent, like in a cookie or something, every time you reload your JS starts all over. Commented Jan 14, 2012 at 14:19
  • you're decrementing number in your for loop 4 times. Change it to for (i = 0; i < 1; ++i) { and it will work. But what's the point of the loop in that case? Commented Jan 14, 2012 at 14:21
  • it's not clear what you're trying to accomplish here, the for loop doesn't make sense at all and you probably don't need it. If you want to count down 3 times then hold two counters (like number, and round), decrease number every time, and add special handling when number reaches 0. Commented Jan 14, 2012 at 14:23

1 Answer 1

1

I take it you want to count down from 25 for 3 times, and then reload the page. Am I right?

var number = 25;
var i = 0;

function countdown() {

    $('#display').html("Redirecting in " + number + " second(s).");

    number--;

    if (number == 0) {

        number = 25;
        i++;

    }

    if (i == 3) {

        window.location.reload();

    }

    setTimeout(countdown, 1000);

}

$(document).ready(function() {
    countdown();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Count down and reload 3 times if thats possible. if not is it possible to count down and reload an iframe
There are a few ways of doing it. I think I'd save myself the trouble and set a session in PHP. Then let PHP output a small code of JS that would set your i value. The session itself would obviously increase each page request. Though manual reloads would also increase the i value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.