2

I'm trying to create a simple timer in javascript that counts down from 5 to 0 on a push of a button. This is my function that I have for the onclick of the button. I'm getting stuck though since it is not counting down. Any hints to where my logic is wrong would be apprciated. Thanks.

function countdown(num) {
    if (num >= 0) {
        document.getElementById("counter").innerHTML=num;
        timer=setTimeout("countdown()", 1000);
        num--;
    }
    else 
        clearTimeout(timer);
}

2 Answers 2

6

The main problem is your evaluation of countdown as a string was not properly passing num along. Try using a function expression instead.

function countdown(num) {
    if (num >= 0) {
        document.getElementById("counter").innerHTML=num;
        setTimeout(function () { countdown(num - 1) }, 1000);
    }
}

Additionally there is no need for a clearTimeout or a global timer value.

Sign up to request clarification or add additional context in comments.

2 Comments

nor is there a need for the timer variable, or num--, correct?
The logical error was not passing in num, however it is acceptable to use strings here, as it just calls eval() on it if you do: setTimeout("countdown("+(num-1)+")", 1000);
1

How about this?

button.onclick = function () {
    var n = 5;

    (function loop() {
        label.textContent = n;

        if ( n > 0 ) {
            n -= 1;
            setTimeout( loop, 1000 );
        }
    })();
};

Live demo: http://jsfiddle.net/YhBx6/1/

Comments

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.