0

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);
    }

}
ManOfPanda
  • 35
  • 7
  • 1
    This question has been asked and answered probably half a dozen times. You need to read up on exactly what `this` means and where it comes from. Did you try debugging this? Simply putting a breakpoint on the line in question and examining the value of `this` would have given you all the clues you needed. –  Sep 06 '14 at 07:13
  • Also see Mike West's [Scope in JavaScript](http://www.digital-web.com/articles/scope_in_javascript/). Mike is a very good writer, and the article is very well written. – jww Sep 06 '14 at 08:52
  • http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback, http://stackoverflow.com/questions/1101668/how-to-use-settimeout-to-invoke-object-itself, http://stackoverflow.com/questions/21429255/why-is-an-anonymous-function-required-to-preserve-this-using-settimeout, http://stackoverflow.com/questions/21370768/setinterval-callback-with-context, http://stackoverflow.com/questions/11931612/about-settimeout-interval-context/11931662#11931662, http://stackoverflow.com/questions/3308790/javascript-context-problem-using-setinterval-with-prototype, and two more. –  Sep 06 '14 at 08:53

2 Answers2

2

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);
    }

}
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95
0

you cant not use this in setInterval use this code

edite this.animate() to example.animate()

use this code

var example = function(){

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

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

}
Behnam
  • 6,244
  • 1
  • 39
  • 36