Tuesday, 7 February 2017

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


}

Answer



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

}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...