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();
jAndy
  • 231,737
  • 57
  • 305
  • 359

6 Answers6

20

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.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 4
    The only 3? What about, well, all the other ones? – Pointy Feb 28 '13 at 16:54
  • 1
    Which other ones? There are no other ones. Assigning an onclick or onreadystatechange (for instance) is just a bastardization of `addEventListener`. – Halcyon Feb 28 '13 at 16:56
  • 3
    What about XHR? What about all the APIs available in Node.js? – Pointy Feb 28 '13 at 16:58
  • 1
    `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. – jAndy Feb 28 '13 at 16:58
  • You bind to XHR with `onreadystatechange` using `addEventListener` or directly if you prefer the bastardized form. If Node.JS adds more functions that behave asynchronously that's fine. Under the hood it's probably just an event dispatcher, I wouldn't be surprised to find another `addEventListener` there. – Halcyon Feb 28 '13 at 16:58
  • Anyway I'm starting to think that I don't agree with myself, in that really *all* JavaScript functions are "synchronous". A call to `setTimeout()` does what it does, synchronously; the call to the timeout handler is also synchronous, though it happens later on. – Pointy Feb 28 '13 at 17:01
  • Yes, exactly. The asynchronousness is not in the functions, it's in whatever calls the functions that is outside of JavaScript. The browser, the runtime, the OS? What have you. – Halcyon Feb 28 '13 at 17:02
  • 1
    @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. – jAndy Feb 28 '13 at 17:03
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();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    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 ^^ – Vincent Jan 15 '15 at 10:36
  • 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 – NiCk Newman Mar 07 '16 at 13:35
5

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.

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.

Brian Hoover
  • 7,861
  • 2
  • 28
  • 41
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.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
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.

David W
  • 10,062
  • 34
  • 60