5

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.

MizzJop
  • 53
  • 1
  • 1
  • 4

5 Answers5

7

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

Karoly Horvath
  • 88,860
  • 11
  • 107
  • 169
6

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

Community
  • 1
  • 1
Tgr
  • 25,494
  • 11
  • 77
  • 108
  • Yeah, thats definitely a nice way of doing this. http://www.erichynds.com/jquery/using-deferreds-in-jquery/ explains this nicely. The only catch being you need to use Jquery 1.5 or above – rajasaur Jul 02 '11 at 13:19
  • Warning: As of jQuery 1.8, the [deferred.then()](http://api.jquery.com/deferred.then/) method (...) replacing the now-deprecated deferred.pipe() method – T30 Oct 09 '14 at 08:39
0

call showStuff in the success callback of ajax call that loadStuff makes.

See also How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Community
  • 1
  • 1
Murali VP
  • 5,549
  • 4
  • 25
  • 35
0

They do run sequentially, but stuff inside loadStuff may not be (especially if loadStuff is performing asynchronous HTTP requests). It's the code inside loadStuff that's not running sequentially.

Usually I'd just say "we need way more code context to answer this question", but there's enough to say this:

Either use a synchronous HTTP request, or move the call to showStuff into the on-success callback for your asynchronous one, so that it only fires when the request has completed.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
0

You can:

Pass showStuff as a delegate to a callback to be invoked upon a successful response from your AJAX call within loadStuff().

Example:

function loadStuff() {

      $.ajax({
      url: "Stuff/GetStuff",
      success: function(){
        showStuff();
      }
    });

}

Or, the less elegant way, just check to see if data is loaded every so often, until it is:

var timerId = setInterval(showStuff, 50);

function showStuff() {
  if (stuffIsLoadded) {
    // do show stuff stuffs.
    clearInterval(timerId);
  }
}
Kon
  • 25,664
  • 11
  • 56
  • 84