Javascript setInterval function not defined

What is wrong with this code. It seems I am getting an error that the 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";
            }
+5
source share
1 answer

Do not pass the string to setInterval.

Your function is a local variable that does not exist if setTimeouteval is a string in the global scope.

Instead, pass this function to setInterval:

var counter = setInterval(timer, 1000);
+8
source

All Articles