skip to Main Content

I can’t understand In which order will the functions foo and bar be executed?

1- foo and bar will execute in the same time, or 2- foo then bar or 3- bar then foo, I think 1- but I don’t sure

var res = {};

function foo(results) {
    res.foo = results;
}

function bar(results) {
    res.bar = results;
}

// ajax (..) is some arbitrary function given by a library
ajax( "http://some.url.1", foo );
ajax( "http://some.url.2", bar );

3

Answers


  1. You removed the correct answer from your question in your first edit. It’s: "2- We don’t know"

    You can’t know the order without knowing the implementation (or documentation) of ajax. The order could even change between different runs.

    Here is an example:

    function ajax(url, fn) {
        setTimeout(fn, Math.random() * 1000);
    }
    
    var res = {};
    
    function foo(results) {
        res.foo = results;
        console.log('foo');
    }
    
    function bar(results) {
        res.bar = results;
        console.log('bar');
    }
    
    // ajax (..) is some arbitrary function given by a library
    ajax( "http://some.url.1", foo );
    ajax( "http://some.url.2", bar );

    You can run it multiple times and the order changes. Sometimes it’s

    foo
    bar
    

    and sometimes it’s

    bar
    foo
    

    but the functions will never be called at the same time.

    Login or Signup to reply.
  2. foo and bar will execute in the same time

    JavaScript generally operates on a single event loop. Unless you farm out processing to a Worker you will never have two functions running at the same time.

    2- foo then bar or 3- bar then foo, I think 1

    You haven’t shown us the ajax function, but assuming it makes an HTTP callback and then queues the callback function up to be called once the complete HTTP response has arrived:

    The order will depend on how quickly the server responds to each of the two different HTTP requests and how long it takes for the browser to receive the response.

    For example, http://some.url.1 might cause the server to spend 30 seconds doing a really complete database query before responding, while http://some.url.2 might do something simple that gets a response after 3ms: In which case bar would be added to the queue before foo and thus run first.

    Login or Signup to reply.
  3. We can’t predict the order of the functions foo & bar. These functions depends on ajax request to an api, so whichever ajax request completes first, it will call the corresponding function.

    Note: If you need to do synchronize both the functions together, then you can use a promise method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search