Pablo Christiano
Pablo Christiano

Reputation: 435

javascript interval in Object

i've wrote a snippet which should start counting a number from 1 to 1000 or pre defined.

Because of needing the script mulitple times i thought it would be a great idea to write it as an object and use it mulitiple times. But i get an error:

Uncaught ReferenceError: root is not defined (anonymous function)

What did i wrong?

     var time = function() {
        var root = this;
        var i=0;
        root.max = 1000;
        root.elm = false;
        root.runTime = function() {
            if(root.elm != false) {
                if (i < root.max) {
                    i++;
                    root.elm.text(i);
                } else {
                    clearInterval(root.interval);
                }
            }
            this.interval = setInterval('root.runtTime()', 5);
        };
    };

    if($(document).ready(function() {
        var countUp= new time();
        countUp.max = 1526;
        countUp.elm = $("#elm");
        countUp.runTime();
    });

Upvotes: 3

Views: 1364

Answers (1)

Curtis
Curtis

Reputation: 103368

This is because of the following line:

this.interval = setInterval('root.runtTime()', 5);

Because it's a string it has to be evaluated as a global object.

Change to the following to ensure the same scope:

this.interval = setInterval(root.runtTime, 5);

Also there's a typo (runtTime should be runTime), so change to the following:

this.interval = setInterval(root.runTime, 5);

Finally you're using setInterval which will repeatedly call root.runTime every 5ms. Change to setTimeout if you wish to call this recursively:

this.interval = setTimeout(root.runTime, 5);

Alternatively set up the interval outside of your runTime function:

   root.runTime = function() {
        if(root.elm != false) {
            if (i < root.max) {
                i++;
                root.elm.text(i);
            } else {
                clearInterval(root.interval);
            }
        }
    };
    this.interval = setInterval(root.runTime, 5); 

Also you don't need the if statement around document.ready. This is a callback function which is triggered when the DOM has loaded, and therefore doesn't require an if statement.

$(document).ready(function() {
    var countUp= new time();
    countUp.max = 1526;
    countUp.elm = $("#elm");
    countUp.runTime();
});

Upvotes: 6

Related Questions