Nistor Alexandru
Nistor Alexandru

Reputation: 5393

Javascript setInterval function not defined

What is wrong with this code I seem to be geting an error that timer is not defined

var counter = setInterval("timer()",1000);

            function timer(){
                count = count-1;
                if(count <=0){
                    clearInterval(counter);
                    return;
                }
                document.getElementById("timer").innerHTML = count + " sec";
            }

Upvotes: 6

Views: 6209

Answers (1)

SLaks
SLaks

Reputation: 887459

Don't pass a string to setInterval.

Your function is a local variable, which doesn't exist when setTimeout eval's the string in the global scope.

Instead, pass the function itself to setInterval:

var counter = setInterval(timer, 1000);

Upvotes: 9

Related Questions