MizzJop
MizzJop

Reputation: 63

How to make jQuery functions sequential

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.

Upvotes: 6

Views: 14368

Answers (5)

Kon
Kon

Reputation: 27431

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);
  }
}

Upvotes: 0

Tgr
Tgr

Reputation: 28160

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

Upvotes: 6

Murali VP
Murali VP

Reputation: 6417

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?

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

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

Upvotes: 7

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385106

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.

Upvotes: 0

Related Questions