Search code examples
javascriptsetintervalundefined-function

Error when calling a method in a setInterval


I am having trouble calling methods in a setInterval... Here is a snippet of my code...

var example = function(){

    this.animate = function(){
        console.log("Animate.");
    }

    this.updateTimer = function(){ // This is being called...
        this.timer = setInterval(function(){
            this.animate(); // A "Undefined Is Not A Function" error is being thrown here.
        }, 1);
    }

}

Solution

  • USE BIND (as @torazaburo said)

    maybe best-practice

    http://jsfiddle.net/rnrlabs/Lnmex1y7/

    var example = function(){
        this.animate = function(){
            console.log("Animate.");
        }    
        this.updateTimer = function() { // This is being called...
            this.timer = setInterval(this.animate.bind(this), 1);
        }
    }
    

    OR.. USE A CLOSURE

    http://jsfiddle.net/rnrlabs/zk6hdnf2/

    var example = function(){
    
        var self = this; // this creates a closure
    
        this.animate = function(){
            console.log("Animate.");
        }
    
        this.updateTimer = function(){ 
            this.timer = setInterval(function(){
                // 'this' here means window element.
                self.animate(); 
            }, 1);
        }
    
    }