Search code examples
javascriptjquerycountdown

Count down from 10 and repeat it when the timer has reacted 0


I want to count down from 10 seconds to 0. When it have reached 0 the DIV will reload and the timer will start over again. I have this function that allows it to do exactly like I wanted but the problem is that when the countdown have reached 0 and going back to 10, it will count -1 reload -2 reload -3 reload -4 reload and so on. That is not how I want it! :)

Here's my code:

var time = setInterval(countdown, 1000);
function countdown() {
    var count = 10;
    countdown = setInterval(function() {
        $('#countdown').html(count + ' sekunder kvar');

        if(count == 0) {
            $('#weather-data').load('jquery-fetch/fetch-weatherdata.php?place=' + myplace);
            clearInterval(countdown);
        }

        count--;
    }, 1000);
}

How can I fix my problem so the timer counts down from 10 to 0 and repeat that countdown forever?

Thanks in advance.

EDIT

When this function has reached 0 for the first time and starts over, it counts like this: 10, 9, 8, 10, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8, 7, 10, 6, 5, 4, 3, 2, 1, 10, 9, 8, 10, 7, 6, and so on. Why does it act like this with this code?

function countdown() {
    var count = 10;
    var timerId = setInterval(function() {
        $('#countdown').html(count + ' sekunder kvar');
        count--;

        if(count == 0) {
            $('#weather-data').load('jquery-fetch/fetch-weatherdata.php?place=' + myplace);
            clearInterval(timerId);
            countdown();
        }
    }, 1000);
}

countdown();

Thanks in advance!


Solution

  • I see a lot of problems in your script... So not sure how you even get that to work..

    1. Function name can't have -, so that call won't work :S
    2. countdown is a global variable inside your function countdown() which is the same as your function name, effectively a countdownception
    3. You are effectively creating a new Interval every one second as you are calling countdown

    To achieve what you want, try the simpler:

    function countdown() {
        // your code goes here
        var count = 10;
        var timerId = setInterval(function() {
            count--;
            console.log(count);
    
            if(count == 0) {
                // your code goes here
                count = 10;
            }
        }, 1000);
    }
    
    countdown();
    

    http://jsfiddle.net/Xrbm5/13/