Question

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!

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top