Force Javascript function call to wait until previous one is finished
javascript, jquery
Solution
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
});
});
Problem
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!