6

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.

5 Answers 5

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

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

Comments

6

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

2 Comments

Yeah, thats definitely a nice way of doing this. erichynds.com/jquery/using-deferreds-in-jquery explains this nicely. The only catch being you need to use Jquery 1.5 or above
Warning: As of jQuery 1.8, the deferred.then() method (...) replacing the now-deprecated deferred.pipe() method
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.

Comments

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?

Comments

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

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.