I’m trying to understand why I’m getting different results when I’m working with callback functions and closures.
The first scenario:
var cb = function(){
console.log("anim done");
}
var anim = Raphael.animation({
transform: 't0, 100'
}, 2000, cb);
circle.animate(anim);
When running this, the circle in question animates, and after 2 seconds the a “anim done” message is displayed in the console.
The second scenario:
var cb = function(msg){
console.log("anim done");
}
var anim = Raphael.animation({
transform: 't0, 100'
}, 2000, cb("test"));
circle.animate(anim);
This causes the callback (cb) to be executed immediately. This results in the “anim done” message to be displayed right away.
Can someone clarify what is actually happening here?
When you provide a callback, it must be a function.
cb("test")is not a function — it’s the return value of a function. If you return something fromcb("test")that is a function, it would work as expected.As it is, you should do this:
This way you pass a function, and not an already-evaluated expression, to the animation.