admin管理员组

文章数量:1302278

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";
            }

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";
            }
Share Improve this question asked Jul 11, 2012 at 17:30 Nistor AlexandruNistor Alexandru 5,3939 gold badges50 silver badges71 bronze badges 1
  • You need to pass the function, not a string, as first param. – Gabriel Santos Commented Jul 11, 2012 at 17:34
Add a ment  | 

1 Answer 1

Reset to default 9

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);

本文标签: Javascript setInterval function not definedStack Overflow