开发者

Force Javascript function call to wait until previous one is finished

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 开发者_JAVA技巧on getting these to execute only one at a time?

Thanks!


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜