views:

436

answers:

5

I have a simple Javascript function:

makeRequest();

It does a bunch of stuff and places a bunch of content into the DOM.

I make a few calls like so:

makeRequest('food');
makeRequest('shopping');

However, they both fire so quickly that they are stepping on each other's toes. Ultimately I need it to have the functionality of.

makeRequest('food');
wait....
makeRequest('shopping'); only if makeRequest('food') has finished

Thoughts on getting these to execute only one at a time?

Thanks!

A: 

They do only execute one at a time. There must be something inside those functions that is executing asynchronously - an AJAX request, perhaps?

Kylotan
Yes, you're correct. Is there anything I can do?
mwilliams
+7  A: 

If these functions actually do an AJAX request, you are better keeping them asynchronous. You can make a synchronous AJAX request but it will stop the browser from responding and lead to bad user experience.

If what you require if that these AJAX requests are made one after the other because they depend on each other, you should investigate your function to see if it provides a callback mechanism.

makeRequest('food', function()
{
    // called when food request is done
    makeRequest('shopping');
});

Using jQuery, it looks something like that

$.get("/food", function(food)
{
    // do something with food

    $.get("/shopping", function(shopping)
    {
        // do something with shopping
    });
});
Vincent Robert
+1 This is the way to go.
ChaosPandion
Getting closer. I tried your first example and makeRequest with shopping isn't called. I can toss an alert and it's not getting triggered either
mwilliams
That means you did something wrong. Why don't you post what you did?
ChaosPandion
I was able to utilize the callback to avoid the toe stepping; thanks!
mwilliams
A: 

I would recommend that you simply write them asynchronously--for example, call makeRequest('shopping'); from the AJAX completion handler of the first call.

If you do not want to write your code asynchronously, see Javascript Strands

Dark Falcon
A: 

I suppose that you have a callback method that takes care of the response for the request? Once it has done that, let it make the next request.

Declare an array for the queue, and a flag to keep track of the status:

var queue = [], requestRunning = false;

In the makeRequest method:

if (requestRunning) {
   queue.push(requestParameter);
} else {
   requestRunning = true;
   // do the request
}

In the callback method, after taking care of the response:

if (queue.length > 0) {
   var requestParameter = queue.splice(0,1)[0];
   // do the request
} else {
   requestRunning = false;
}
Guffa
A: 

If you need to make a number of requests execute sequentially, see Peter Baker's answer to a similar question of mine.

Rich Seller