1

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/

3 Answers 3

5
"complete": complete( "3rd" )

This line will execute the complete function, passing in a parameter of "3rd" and then set the returned value of that function to "complete".

"complete": function(){ complete( "2nd" ); }

This line will instead set "complete" to a function, which, when called, will execute the complete function, passing a parameter of "2nd".

Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

This was very clear. It made me realize the parens make the call, like the pattern: (function(){...})();. Knowing that it returned undefined, and that it is expecting a function declaration instead, lead me to a rewrite of complete() that works and still maintains the concise readability of "complete": complete( "3rd" ). New function: function complete( ordinal ){ return function(){ ... }; };.
0

On your last part, wrap it in a function:

.delay(1000).animate( 
    { "width":    "500px" }, 
    { "duration": 3000,
      "complete": function(){complete( "3rd" ) }
    }
);

If you don't do this then the function gets called immediately, which is not what you wanted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.