ThinkingStiff ThinkingStiff - 13 days ago 5
Javascript Question

Understanding JavaScript anonymous vs. named functions in object literals

Why does the "complete" callback for the third animation happen first, before any animations have started?

Script:

$( "#animate" ).delay(2000).animate(
{ "width": "500px" },
{ "duration": 3000,
"complete": function(){ $( "#animate" ).append( "1st<br />" ); }}
)
.delay(1000).animate(
{ "width": "200px" },
{ "duration": 3000,
"complete": function(){ complete( "2nd" ); }}
)
.delay(1000).animate(
{ "width": "500px" },
{ "duration": 3000,
"complete": complete( "3rd" ) }
);

function complete( ordinal ){
$( "#animate" ).append( ordinal + "<br />" );
};


HTML:

<div id="animate" />


CSS:

#animate
{
border: 1px solid red;
height: 200px;
width: 200px;
}


jsfiddle:

http://jsfiddle.net/nQftS/3/

Answer

The callback expects a function. You, however, do not pass a function. You call a function.

  "complete": complete( "3rd" )

which appends things as defined within that function. It then returns nothing, so it evaluates to:

  "complete": undefined

Note that passing a function works without parentheses. E.g.

  "complete": complete

or

  "complete": function() { ... } // this is also a function