Casey Dwayne
Casey Dwayne

Reputation: 2169

Why is my jquery callback firing early?

Even with .promise().done() my callback function fires early..

Why?

Fiddle

title.delay(1000).show(1200).promise().done( function(){
  menu.show(0, function(){
    menu.find('*').show(600, message())
  })      
})  

message = function(){ alert('done'); }

Upvotes: 2

Views: 1658

Answers (1)

mishik
mishik

Reputation: 10003

This code:

menu.find('*').show(600, message())

Needs to be:

menu.find('*').show(600, message)

The difference is: in the first example you effectively pass two arguments:

  1. 600
  2. result that is returned by function message (which is undefined here)

Because () - is the operator to call function in JavaScript.

In the second example, however, you pass 600 and function message.

As @FakeRainBrigand noted - if you want to supply arguments to the function - you have several ways:

  1. Use message = message.bind(<context>, param1, param2,...). Then any time you call message it will be called with <context> as this and param* as arguments.
  2. Use wrapping function:

.show(600, function() {
   message(param1, param2, ...);
});

Upvotes: 6

Related Questions