Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    });
like image 497
Pablo Christiano Avatar asked Nov 19 '25 05:11

Pablo Christiano


1 Answers

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();
});
like image 127
Curtis Avatar answered Nov 21 '25 18:11

Curtis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!