简体   繁体   English

使用setTimeout时“功能未定义”?

[英]“function is not defined” when using setTimeout?

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. 一旦获得s​​etTimeout,它就会吐出“未捕获的referenceerror:未定义getnumbers(其中,getnumbers只是变量的名称。

$(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! 谢谢!

setTimeout with a string argument is just a global eval . 带有字符串参数的setTimeout只是一个全局eval When it tries to evaluate getnumbers.countDigit() , it is evaluated in the global scope, and no longer has access to getnumbers . 当它尝试评估getnumbers.countDigit() ,将在全局范围内对其进行评估,并且不再有权访问getnumbers

Solution: Don't pass in a string. 解决方案:不要传入字符串。 Instead, try this: 相反,请尝试以下操作:

setTimeout(getnumbers.countDigit, 3000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM