Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make jQuery functions sequential

Tags:

jquery

I have the following code:

$(document).ready(function() {
  loadStuff(someURL, someID);
  showStuff('foo');
});

showStuff() relies on content generated by loadStuff() but it seems as if showStuff() is jumping the gun before said content is available. How can I force them to run sequentially?

Update: Yes, there are ajax calls in loadStuff but unfortunately they're jsonp so can't be called synchronously.

like image 439
MizzJop Avatar asked Jul 02 '11 12:07

MizzJop


2 Answers

rewrite it as:

$(document).ready(function() {
  loadStuff(someURL, someID, function() { showStuff('foo'); });
});

where the third parameter of loadStuff is the callback to call after the content is loaded

like image 134
Karoly Horvath Avatar answered Sep 18 '22 13:09

Karoly Horvath


The elegant way is using jQuery.Deferred, in particular Deferred.pipe. See the question Understanding jQuery Deferred.pipe() for an example.

like image 36
Tgr Avatar answered Sep 19 '22 13:09

Tgr