I am making an ajax call to the server. The code I need to run can be divided into 3 groups.
- Code that needs to run before the ajax call ins made (preparing the json object going to the server)
- Code that needs to be run after the ajax call has returned (uses what was sent back from the server)
- Code that needs to be run between the time the user presses a button and the time everything is done. This code does not need the returned json object.
It would be ideal to run the code in group 3 after making the ajax call and before the results are back to gain the best user experience and performance.
Can this be done?
How?
Very simply:
This works because JavaScript is synchronous in execution (unless workers are being used, but that’s unrelated to this particular issue). The first bit of code will run, then the ajax call will tell the browser to start an XHR request, but
someFunctionhasn’t finished, so it will continue to execute synchronously.Once
someFunctionis done, the control flow will be opened up to any asynchronous events that occur, eventually leading to thedonecallback.To be fair, asynchronous event-oriented programming is not easy for most people to wrap their heads around. It’s easy to lose track of what code is supposed to occur at what time.
Here’s an easily executable example of how asynchronous behavior works:
The order of alerts will be
1,3,2.setTimeoutwill not call its callback synchronously as it relies on waiting for the specified amount of time to elapse, so even if no time is supposed to elapse, it still has to wait for the current function to finish before it can continue.