javascript - "function is not defined" when using setTimeout? - Stack Overflow

For whatever reason, I can't get this function repeat.Once it gets the setTimeout, it spits out

For whatever reason, I can't get this function repeat. Once it gets the setTimeout, it spits out the "uncaught referenceerror: getnumbers is not defined (where getnumbers is just the name of the variable.

$(document).ready(function(){


    var getnumbers = {

        countDigit: function(){

            if (sessionStorage.counter=="NaN"){
                sessionStorage.counter="0";                                   
            }
            else {
                sessionStorage.counter=Number(sessionStorage.counter)+1;

            }

            $("#result").text("counter: " +sessionStorage.counter);

            setTimeout("getnumbers.countDigit()",3000);             

        },

        _init: function(){
            getnumbers.countDigit();    
        }
    };

    getnumbers._init();     

})
    

Ironically, if I refresh the page the counter works, so I know it's just getting stuck on that one line. What could I be missing?

Thanks!

For whatever reason, I can't get this function repeat. Once it gets the setTimeout, it spits out the "uncaught referenceerror: getnumbers is not defined (where getnumbers is just the name of the variable.

$(document).ready(function(){


    var getnumbers = {

        countDigit: function(){

            if (sessionStorage.counter=="NaN"){
                sessionStorage.counter="0";                                   
            }
            else {
                sessionStorage.counter=Number(sessionStorage.counter)+1;

            }

            $("#result").text("counter: " +sessionStorage.counter);

            setTimeout("getnumbers.countDigit()",3000);             

        },

        _init: function(){
            getnumbers.countDigit();    
        }
    };

    getnumbers._init();     

})
    

Ironically, if I refresh the page the counter works, so I know it's just getting stuck on that one line. What could I be missing?

Thanks!

Share Improve this question edited Mar 16, 2012 at 3:50 user166390 asked Mar 16, 2012 at 3:46 tlflowtlflow 1651 gold badge3 silver badges10 bronze badges 1
  • stackoverflow./questions/3741503/… – user166390 Commented Mar 16, 2012 at 3:51
Add a ment  | 

1 Answer 1

Reset to default 6

setTimeout with a string argument is just a global eval. When it tries to evaluate getnumbers.countDigit(), it is evaluated in the global scope, and no longer has access to getnumbers.

Solution: Don't pass in a string. Instead, try this:

setTimeout(getnumbers.countDigit, 3000);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745236048a4617897.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信