Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setInterval function not defined

Tags:

javascript

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";
            }
like image 458
Nistor Alexandru Avatar asked Jul 11 '12 17:07

Nistor Alexandru


1 Answers

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);
like image 165
SLaks Avatar answered Sep 18 '22 10:09

SLaks