16

Consider the following function being executed,

function loadPage()
{
    takeInput();
    processInput();
    outputInput();
}

In what order would they be executed(I have read that it follows stack so option 2 will be the answer)?

Option #1

  1. takeInput();
  2. processInput();
  3. outputInput();

Option #2

  1. outputInput();
  2. processInput();
  3. takeInput();

6 Answers 6

21

JavaScript functions are not asynchronous. Some very limited set of functions have an asynchronous API:

addEventListener, setTimeout, setInterval. These are the only 3 (which I thought was very surprising).

They allow you to pass in a callback that may get called eventually. Such as when a timer expires, or when a user clicks on something, or when an AJAX request completes.

JavaScript has an event loop. The event loop processes each event as it comes in. If you click a button 3 times and then a timer expires that will also be the order the events are handled. It is all very well defined and determined.

Furthermore, JavaScript doesn't have threads, it runs one event completely till there is nothing left to do (you return) before starting the next event. So events will never interfere in any way. This allows you to make very strong assumptions about the state of your data.

Sign up to request clarification or add additional context in comments.

8 Comments

The only 3? What about, well, all the other ones?
Which other ones? There are no other ones. Assigning an onclick or onreadystatechange (for instance) is just a bastardization of addEventListener.
What about XHR? What about all the APIs available in Node.js?
XHR callbacks in general work async, "new" APIs like setImmediate(), and don't forget about nodeJS, there almost every function/callback works async by default.
@Pointy: yes. Thats the reason why I think its wrong to say that only "these" functions work async. Alot of processes and callbacks work async, which basically means, that some functionality is added to the UI queue, not more not less. Many events (especially DOM events) are just instantanously added to this queue and some later on. Imho, you can't nail it down, since several code is moved indirectly into the UI queue.
|
11

Are JavaScript functions asynchronous?

Some are, most are not.

In what order would they be executed

They will be executed in the order in which they are called. Since they are are all called from the same function, that will be in a simple linear order.

If any of them are written in an asynchronous way, then they might not finish all their activity in the same order. For example:

function a() {
   console.log('a'); 
}
function b() {
   console.log('b'); 
}
function c() {
   console.log('c'); 
}
function aAsync() {
  setTimeout(a, 500); 
}

function load() {
   aAsync();
   b();
   c();
}
load();

2 Comments

So c() will always wait for b() to be completed as long as all code in b is synchronous? So b can contain 1000 lines of syncronous code & c will still be executed after b than? Just making sure ^^
Good example that highlight the order of operations when the code is asynchronous inside the parent functions. Will be a slaughterhouse if we start adding async code inside b, c. By that, we should be using Promises :D
6

Javascript is not Asynchronous.
It works Synchronously ,that is it runs one line of code at a time. When javascript code is run , first a Global execution context is created and if you call a function from global execution context, another execution context is created by the javascript engine and that is placed at the top of the execution stack (global execution context is already in the stack)and if there is another function being called from inside that function ,another execution context is created and stack size keeps on increasing.

So,javascript engine keeps running this code one line at a time and in that process if there is any event/ http request fires, the browser puts them in the EVENT QUEUE. So, the point is javascript engine wont process the events in queue until the execution stack is empty. And when the engine is done with the execution stack, it periodically looks if there is any event handler for current event in queue and similarly creates execution context for that handler and runs the code within. So, the whole process is just synchronous and asynchronousity is just handled by the other parts of browser like(rendering engine or http engine) while the javascript engine continues to run the code synchronously.

So, in your case, from whichever context function loadpage was invoked , its execution context was created and and placed at the top of the stack. Then, it invokes the takeinput function, its exec. context is created and and other functions context will not be created and placed in the stack until the takeinput context is popped out from the execution stack. So, the correct order will be takeinput, processinput and outputinput.

I hope it answers your question.

Comments

1

JavaScript is not, generally asynchronous, but it does have asynchronous and event driven methods.

Ajax calls are the big asynchronous methods.

For events, I'm not sure that you can be guaranteed about an order of execution, but I might be wrong about that.

Comments

0

No, not by default/as standard, though there are asynchronous methods. And jQuery makes use of asynchronous behaviour much more so. But in each case, it's subjective, and can't be said that "All of the JavaScript is this or that".

Methods are always executed in the order they are called; the asynchronousness of them means that any may complete before another, even if called afterwards.

Comments

0

Javascript is a single-threaded beast, so strictly speaking tasks are not asynchronous as one might think of in terms of spawning child threads to execute code. The mechanisms that provide this create the illusion of asynchronicity, but its still single-threaded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.