Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 on getting these to execute only one at a time?

Thanks!

like image 674
mwilliams Avatar asked Oct 09 '09 23:10

mwilliams


People also ask

How do you wait till setTimeout to finish?

Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.

How do I make a function wait before returning?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

How do I force a JavaScript wait?

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console.log("Hello"); setTimeout(() => { console.log("World!"); }, 5000); This would log “Hello” to the console, then make JavaScript wait 5 seconds, then log “World!”


2 Answers

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
    });
});
like image 118
Vincent Robert Avatar answered Oct 12 '22 01:10

Vincent Robert


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

like image 26
Dark Falcon Avatar answered Oct 12 '22 01:10

Dark Falcon