How is a function made inherently asynchronous in JavaScript - javascript

I have been trying to understand how asynchronous JavaScript works. From what I understand, the language is by-default synchronous and single-threaded.
Synchronous in the sense that during the processing of the current task, rest of the code is blocked.
Single-Threaded in the sense that only one sequence of functions is loaded at a time. To me, both of these concepts sound a bit similar.
I'm aware of how callbacks, promises and async/await keywords help in dealing with asynchronous code. But what I don't understand is, how a block of code is made asynchronous. For example, this is a code from javascript.info:
function loadScript(src) {
// creates a <script> tag and append it to the page
// this causes the script with given src to start loading and run when complete
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
Now, when this function is called, it is supposed to be "asynchronous", in the sense that it won't block the subsequent lines of code from execution, but will carry on it's work "in the background".
loadScript('/my/script.js');
// the code below loadScript
// doesn't wait for the script loading to finish
// ...
What I don't understand is, what part of the function defined above made it asynchronous? The same goes for browser and API functione like fetch() and addEventListener(). What in their implementation made them asynchronous? How is task made to be performed in the background without blocking the rest of the code?

"What part of the function defined above made it asynchronous?"
The above function runs synchronously, but this calls for explanation. In general:
Event Loop
Browsers use an event loop to process "everything", including repainting the screen,
calling JavaScript code when timers expire, promises become settled, events have occurred and need to be fired on DOM elements, or in general calling JavaScript in response to an external event.
Single Thread
The event loop's task manager does not continue with other tasks after passing control to the JavaScript engine to execute JavaScript code. This is the "single threaded" part. JavaScript execution continues until it runs to completion, either by running to the end of top-level execution flow within a script element, or by returning from a call out from the event loop.
Single threading prevents JavaScript execution being interrupted by call outs from the event loop in a different thread with the ability to access the same program scope - which has the potential to corrupt data and program state. Effectively single threading eliminates the need to implement a disable/enable interrupts system in JavaScript.
Note: Multiple JavaScript threads can be created by setting up worker threads running in separate CPU threads. But communication between threads is tightly controlled and they do not share the same program scope.
Blocking
The cost of single threading is that execution of JavaScript in the main thread prevents the event loop task manager from proceeding with anything else. Hence executing JavaScript will block screen updating and responding to user input etc. until it returns to the event loop.
Synchronous
Synchronous code means code executed in a single call out from the event loop. Synchronous code execution flow proceeds through sequential, branch and looping constructs as you would read it in source code.
A synchronous API call is one that returns it result back to the caller with a return statement - without using a callback function or promise to supply the result.
Asynchronous
Asynchronous code is relative to something else: it is code that is not executed in the same call out from the event loop as some other execution context. E.G. a call back function passed to setTimeout is never called before the code that calls setTimeout returns to the event loop, so the call back is said to be called "asynchronously".
async Functions
Functions declared with the async keyword are a special case by design. Briefly
the await operator returns to the event loop when executed. Hence code using the result of an await operator runs asynchronously with respect to code which executed the await operator (or prepared its operand).
async functions always return a promise for the function's return value, not the returned value itself. Since promise values are not available synchronously, async function results can not be obtained synchronously in calling code.
For parts of the question:
What part of a function makes it asynchronous?
Standard functions are not inherently asynchronous: it is how they are called that determines their synchronicity or otherwise. Describing a standard function as an "asynchronous function" would mean it is intended to be called asynchronously. Calling an async function an "asynchronous function" is a simplification: async functions are often called synchronously but always involve asynchronous code execution.
API functione like fetch() and addEventListener()
document.addEventListener("click", event=>console.log("clicked"))
adds the anonymous arrow function as a click event listener. Because the arrow function not called as part of the above script's execution flow, you can say it's called asynchronously when a user clicks the mouse.
Similar considerations apply to fetch: the code calling fetch returns to the event loop, the browser initiates a network request, waits for a response, places a task in a task queue and the event loop task manager calls the fetch callback with data. The callback runs asynchronously with respect to the code that called fetch in the first place.
function loadScript(src) {
// creates a <script> tag and append it to the page
// this causes the script with given src to start loading and run when complete
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
A call to loadScript will execute the function's body code and synchronously return to the caller which continues execution after the call. It does however have side effects:
If loadScript is called while parsing HTML source, the absence of an async attribute on the script element means the HTML parser will stop parsing further HTML source until after the script has been fetched from the location specified in src, parsed by the JavaScript parser and executed. However execution of the loaded script is asynchronous: it only executes after the code calling loadScript returns to the event loop.
If the above code is executed after HTML parsing has reached end of input, the async attribute value is ignored and the script will be loaded asynchronously anyway. Placing "load" and "error" handlers on the script element allows obtaining notification of script load success or failure.

Related

Node JS Processor Architecture

I was trying to fetch a solution to my problem regarding node js architecture.
I know node js is single threaded and works on event looping and non-blocking mechanism.
But my problem is how the processor behind it works does it works synchronously and on a priority basis? or it works on multiple requests simultaneously on a single core machine.
Tried to verify this by creating two API's
In 1st API I created a while loop
whereas in the 2nd API I created a response of hello world.
Then I tried to hit both API's 1st and then 2nd but the second API was waiting for the first to end so here the processor was not working on the second API till the first end.
So can I say that the processor of node js will work in synchronous order but not in parallel?
So all the requests will have to wait in a queue for previous requests to complete?
From my perspective, the thing is, answer to this question is not that simple.
1) If we are talking about ExpressJS then yes it works synchronously
2) But let say we are talking about nodeJs built-in executions, like http module it can make calls asynchronously (but it depends upon OS on which NodeJs is running).
Different modules in NodeJs behave differently from synchronous to asynchronous.
NodeJS V8 based VUlibs which are actually C++ based libraries and most of these libraries use threading mechanism. Like crypto module can run execution asynchronously up to some extent.
Your Javascript is single threaded - ALWAYS and it's not pre-emptive either. So an event occurs, some Javascript starts running in response to that event and NO other Javascript can run until that event handler returns control back to the interpreter by returning from the callback that was called to start the event handler.
At that point, another event can fire and run another event handler and again no other Javascript can run until that event handler returns back to the system.
This is true for ALL Javascript that node.js runs.
Ahhh, but not every thing you do in node.js is actually Javascript. Let's suppose you have two simple timers:
console.log("A");
setTimeout(function() {
console.log("B");
fs.readFile("smallfile.txt", function(err, data) {
console.log("C");
});
console.log("H");
}, 1000);
console.log("D");
setTimeout(function() {
console.log("E");
fs.readFile("bigfile.txt", function(err, data) {
console.log("F");
});
console.log("I");
}, 1000);
console.log("G");
This will log in the console
A
D
G
B
H
E
I
C
F
Let's discuss why it will do this.
The A is obvious, it's the first statement.
Then, the code calls setTimeout() which is non-blocking and asynchronous. So, all it does is schedule a timer for some time in the future and then immediately returns. The setTimeout() callback won't be ready to be called for 1000ms so it doesn't get called right now.
So, next after the setTimeout() call returns, we execute the console.log("D");
Then, it executes the next setTimeout() which again just schedules a timer for 1000ms for now and immediately returns.
Then, it executes console.log("G");.
At this point, it returns control back to the JS interpreter and it has nothing else to do for a little while.
Then, approx 1000ms later, the first setTimeout() timer sticks a timer event in the event queue and since the JS interpreter is not running any other Javascript, it grabs that event and runs the JS callback associated with that event. That immediately logs console.log("B");.
Then, it calls fs.readFile("smallfile.txt", ...). This is again non-blocking and asynchronous so all it does is tell the underlying native code fs module implementation to go read all the data from this file and then returns immediately. It then runs console.log("H");. At this point, it's done with this event handler and returns control back to the interpreter.
Meanwhile, the second setTimeout() event is ready so the JS interpreter pulls that event from the event queue and calls the callback associated with it.
That runs console.log("E"); and then calls fs.readFile("bigfile.txt", ...). This is again non-blocking and asynchronous so all it does is tell the underlying native code fs module implementation to go read all the data from this file and then returns immediately. It then runsconsole.log("I");`. At this point, it's done with this event handler and returns control back to the interpreter.
Some time later, the fs.readFile("smallfile.txt", ...) finishes and inserts an event into the event queue. Since the JS interpreter has nothing else to do, it fetches that event and runs the callback associated with it and we see the results of console.log("C"). That is then finished and returns control back to the interpreter.
Some time later, the fs.readFile("bigfile.txt", ...) finishes and inserts an event into the event queue. Since the JS interpreter has nothing else to do, it fetches that event and runs the callback associated with it and we see the results of console.log("F"). That is then finished and returns control back to the interpreter.
At this point everything is done.
Hopefully you can see how asynchronous operations (implemented in native code can run in parallel with Javascript execution using other CPU cores) and they are synchronized with Javascript execution by placing events in the event queue. When the JS interpreter is done running an event handler, it can then look in the event queue for the next event to run, or if nothing there now, go to sleep until the next event is inserted in the event queue.
So, while native code implementations can run in parallel with Javascript, there's still only one thread of Javascript execution that runs at a time and another one can't run until the prior one returns control back to the interpreter by returning from whatever event handler callback start its execution.
Internally in the event loop, there are actually a bunch of different types of queues that are used for different types of events and they have somewhat different priorities relative to one another so it's all a little more complex than I've described it here, but the core concept is an event driven system that runs the Javascript associated with only one event at a time (single threaded) and native code implementations of some operations that can run in a parallel with Javascript execution that are synchronized with Javascript's single thread of execution via the event queue.

where do the browser web api's run in Javascript?

where do the browser web api's run in Javascript like setTimeout ?
Do they run in some other environment or they take the help of javascript single thread ?
They run outside of the JavaScript runtime. Those "Web API's" are executed within the browser's Web API execution space.
setTimeout() for example, is a method of the window object (it can also be invoked as window.setTimeout()). window is not at all part of JavaScript (it's a browser object) and anything you ask the window to do for you is handled outside of the JavaScript runtime and by the browser's other capabilities. The request for the Web API call originates from within the JavaScript environment, but the execution of the API call actually runs outside of it.
This is the very reason that we can have asynchronous behavior in web applications. While the JavaScript runtime (which is a synchronous environment that can only do one thing at a time) is doing its one thing, the browser can be doing something else.
setTimeout(), alert(), navigator.geolocation, XMLHttpRequest are all examples of Web APIs that run outside of the JS engine.
Here are some other Web API's and here is a great video that explains this in the context of timers specifically.
The following series of events occur when the API calls are made:
When the browser makes an API call, the API call is placed in the call stack
API call is placed in the browser's web APIs stack for execution in the background
While the API call is being executed in web APIs background, the render queue tasks are passed to the call stack by the event loop (assuming all tasks in call stack are complete) - this means the render queue is not actively paused hence the browser is not freeze
Once the API call is completed, the results are placed to the callback queue
If the call stack is clear, the results of the API response are placed to the call stack and the API response handler is executed by the call stack
Do comment if you need any clarification
APIs in client-side JavaScript:
To understand how browser APIS works, first, you have to clear concept about execution stack, event loop and message queue
Client-side JavaScript, in particular, has many APIs available to it — these are not part of the JavaScript language itself, rather they are built on top of the core JavaScript language, providing you with extra superpowers to use in your JavaScript code. They generally fall into two categories:
Browser APIs are built into your web browser and are able to expose data from the browser and surrounding computer environment and do useful complex things with it.
For example, the Web Audio API provides JavaScript constructs for manipulating audio in the browser — taking an audio track, altering its volume, applying effects to it, etc. In the background, the browser is actually using some complex lower-level code (e.g. C++ or Rust) to do the actual audio processing. But again, this complexity is abstracted away from you by the API.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction
<script>
const second = () =>{
console.log("How are you doing");
}
const first = () =>{
console.log("Hi there");
second();
console.log("The End");
}
first();
</script>
Above example is an example of Synchronous JavaScript, where the first function is executed, logs "Hi There!" to the console, calls the second function, which then prints "How are you doing?" to the console,
nd then finally "The end" is logged to the console One instruction after the other in a Synchronous way.
Now let's try by an example with setTimeout which is a web API. considering bellow example
<body>
<script>
const second = () =>{
setTimeout(()=>{
console.log("Async Hi there");
}, 2000)
}
const first = () =>{
console.log("Hi there");
second();
console.log("The End");
}
first();
</script>
</body>
Output:
Now above one involves some Asynchronous JavaScript. Again the first function gets called, logs "Hi There!" to the console, and then calls the second function. Now this function calls the Set Timeout function, which is basically like a timer that will execute the callback function that we passed into it, after 000 milliseconds. However, this will not make the code stop for two seconds, but instead, the function returns, goes back to the first function and logs "The end". Then after the two seconds actually have passed, Async "Hi There!" is logged to the console.
Now, why does the code move on, instead of waiting for the timer to finish?
Well, before I discuss with you how and why this actually works behind the scenes, let me quickly explain to you another example. Suppose we select an image from our DOM and pass it into a Process Large Image function,
that we created. We know that this function is gonna take some time
to process the image. And just like before we don't want the code to have to wait. So we don't want it to stop while the image is processing,
because that would be terrible in some situations. What we do here is to also pass in a Callback function, that we want to be called as soon as the function is done processing. And just like that we have created Asynchronous code.
That is the whole philosophy behind Asynchronous JavaScript. We do not wait for a function to finish its work, and then do something with the result. Instead, we let that function do its job in the background,
so that we can move on with the code execution. We then also pass in a callback function, that will be called as soon as the main function
has done whatever it had to do. We then move on immediately,
so that the code is never blocked. Which means that it can keep processing the code in a Synchronous way, line by line. Because if the code is actually blocked, then nothing really works on the page during that time.
For example you can't click any buttons, or anything like that. So, in summary, we can use callback functions to defer actions into the future.
In order to make our code non-blocking. But how does that actually work
behind the scenes of JavaScript? Well, that's where the Event Loop comes in. the Event Loop is part of the bigger picture of what happens behind the scenes of JavaScript, when we call functions and handle events like DOM events.
Event Loop, as well as the Web APIs, which together with the Execution Stack and the Message Queue make up our JavaScript runtime. This runtime is responsible for how JavaScript works behind the scenes as it executes our code. It's extremely important to understand how all these pieces
fit together in order to execute Asynchronous JavaScript.
Let's now take a look at how the code from the last example
is executed inside our JavaScript engine, line by line.
It starts by calling the first function, and as we already know,
an Execution Context for that function is put on top of the Execution Stack, which can also be called the Call Stack.
In the next line of code, the console dot log function is called and a new Execution Context is created and the text is logged to the console.
Then the function returns and the Execution Context pops off the stack.00
Moving on to the second function, a new Execution Context is created
and in the next line the Set Timeout function is called. Which causes yet another Execution Context to be created.
Now, before we move on, where does this Set Timeout function actually come from? It's part of something called the Web APIs. Which actually live outside the JavaScript engine itself. Stuff like DOM manipulation methods, Set Timeout, HTTP requests for AJAX, geolocation, local storage and tons of other things, actually live outside of the JavaScript engine
We just have access to the because they are also in a JavaScript runtime
This is exactly where the time will keep running for two seconds, asynchronously of course so that our code can keep running without being blocked.
When we call the Set Timeout function the timer is created, together of course with our callback function Right inside the Web APIs environment.
And there it keeps sitting unti it finishes its work all in an Asynchronous way.
The callback function is not called right not but instead it stays attached to the timer until it finishe
And since the timer keeps working basically in the background, we don't have to wait and can keep executing our code. Next up, the Set Timeout function returns, pops off the stack and so does the Execution Context of the second function Which now returns as well and we are back to the initial first function. Now we just log the end to the console
and we give ourselves a new Execution Context, print the text to the console and pop the text off again.
Next the function returns and we are back to our original state
Right now we have executed all our code in a Synchronous way,and have the timer run Asynchronously in the background. Let's suppose that our two seconds have passe and the timer disappear. But what happens to our callback function no Well, it simply moves to the Message Queue
where it waits to be execute as soon as the Execution Stack is empty
This is exactly what happens with DOM events.
In the case of DOM events our event listeners sit in the Web APIs environment, waiting for a certain event to happen And as soon as that event then happen then the callback function is placed on a Message Queue
ready to be execute.
Alright, so how are these callback function in the Message Queue executed
And that's where, finally, the Event Loop comes in. The job of the Event Loop is to constantly monitor the Message Queue and the Execution Stack,
and to push the first callback function in line onto the Execution Stack, as soon as the stack is empty. In our example here, right now the stack is empty, right And we have one callback waiting to be execute
And the event loop takes the callback and pushes it onto the stack
where a new Execution Context is created for that function.
That's what the event loop does. Inside that callback function now,
we simply run the log function, which logs Async "Hi There!" to the console. Then the context pops off the stack and we're done! Now if there were some callbacks waiting right now like data coming back from an AJAX request or the handler of a DOM even then the Event Loop would continue pushing them onto the stack until all of them were processed.

How much further does code execute after an asynchronous function is called

Apologies if the title of this question is slightly confusing, I was struggling to find a way to word this.
Basically, when an asynchronous function is called, how much further down the code will be executed if the asynchronous function is called from other functions, objects, or files. For example:
function func1() {
// async function 1
// async function 2
}
function func2() {
// more code
}
func1();
func2();
Let's say we execute func1() and both the async functions inside of it take a very long time to run. Will we continue on to func2() while the content of func1() is still being run, or will we block until func1() is finished before continuing to func2()?
JavaScript is single threaded, non-blocking and asynchronous language. JavaScript has call stack, event loop and a callback queue. Words are taken directly from this video. Javascript works on v8 engine (chrome), spider monkey (firefox) which provide JavaScript call stack and heap. v8 or spider monkey provide call stack to Javascript so whenever a function is called, it is stored in the call stack of the runtime (browser in our case, local if you have node installed). Browser also provide the web apis to the javascript like setTimeOut, XMLHttpRequest and DOM. The pictorial illustration is something like this. (Source is the same video which I've tagged.)
JavaScript is single threaded and it means it can execute one function at a time as it has only one call stack. So whenever an asynchronous code (inside func1)is executing, it is executed through webAPIs provided by the browser. The role of callback queues come here. Whenever the result from the Async code is executed, it is stored in the callback queue and it waits for the stack to get empty (event driven programming). Whenever it sees that the stack is empty, the function from the callback queues will start executing.
In your case, you're calling func1, it kicks in some async code but currently func1 is in stack. If the async code has completed and if it sees the stack as empty, it will executed the async code first and then func2 but if the async code hasn't completed, it will start executing the func2 and the callback queue will wait for the stack to get empty. In this case, the flow will be func1 --> func2 --> async code.
So, it is matter of timing. For async code, if the code has returned and waiting in callback queue, as soon as it sees the stack empty, it will kick in and start executing the callbacks (.then or callback from setTimeOut etc.) I'll recommend you to watch that video for better insights and what an event loop in JS is. If I'm missing out something, anyone please feel free to edit this answer or provide suggestions for edit.
JavaScript is single threaded, it literally means nothing can be executed in the same time. If your code has asynchronous nature it means that it is executed in uknown future. I said uknown because it depends from the code. For example asynchronous code for ajax call will be executed when the browser gets the response from the server.
That said, the async code is not executed in the declaration moment but in uknown next event loop. Furthermore it not blocks the current execution. In javascript your execution code can not be disturbed. It just runs through all lines.
Going back to the example, if func1 has no sync blocking code then func2 will be executed right away without any delay.
Asynchronous callback are top level events (similar to button click events) and can only be started when there is no other scripts executing.
Execution will continue till call stack is empty (including "global user code" which what your sample shows) and script engine itself gets control back - so both func1() and func2() will finish before callbacks are executed.
Note: you can't rely on such behavior for normal code - if "asynchronous" function has both synchronous and asynchronous code branches callback from that function can be executed synchronously without even returning to calling function (this can happen with plain callbacks or any other form including promises).

Explaining Node Callbacks and Single Threading

Is node's javascript environment single threaded, or does everything happen at the same time? Or (more likely) do neither of those statements explain what's going on with node.
I'm new to node and trying to understand how it processes callbacks. My googling on the subject hasn't proven fruitful, and it seems like there's multiple audiences using terms like "threads, locking, and single threaded" with difference contexts for each audience, and I don't have enough experience with node to correctly parse what I'm reading.
From what I've read, node's javascript execution environment is, like a browser's, single threaded. That is, despite everything being designed around asynchronous callbacks, everything happens in a deterministic order, and there's never two threads modifying the same variable or running statements at the same time. I've also read this means a node programmer-user doesn't have to worry about locking semantics.
If I'm in browser-land and use one of the popular javascript libraries to setup a non-dom-event-handler callback, something like
console.log("Here");
$.each([1,2,3],function(){
console.log("-- inside the callback --");
});
console.log("There");
My output is consistently
Here
-- inside the callback --
-- inside the callback --
-- inside the callback --
There
However, if I do something like this with a callback in node js (running it as a shell script from the command line)
var function example()
{
var fs = require('fs');
console.log("Here");
fs.readdir('/path/to/folder', function(err_read, files){
console.log('-- inside the callback --');
});
console.log("There");
for(var i=0;i<10000;i++)
{
console.log('.');
}
}
example();
console.log("Reached Top");
I consistently (seemingly — see "not much experience" above) get results like this
Here
There
.
. (repeat 10,000 times)
Reached Top
-- inside the callback --
That is, node finishes executing the function example before calling the callback.
Is this deterministic behavior in node? Or are there times where the callback will be called before the example function finishes? Or will it depend on the implementation in the library using the callback?
I understand the idea behind node is to write event based code — but I'm trying to understand what node is really doing, and what behavior can be relied on and what can't.
Is node's javascript environment single threaded, or does everything happen at the same time?
Node has single threaded program execution model, meaning that only one instruction will be executed at any time within one node process. The execution will continue until the program yields the control. This can happen at the end of the program code, or when callback reaches it's end.
In the first case:
console.log("Here");
$.each([1,2,3],function(){
console.log("-- inside the callback --");
});
console.log("There");
they key is the fact that $.each uses callbacks synchronously, so effectively it calls it's callbacks in deterministic order.
Now in the second case, fs.readdir uses callbacks asynchronously - it puts the callback waiting for the event to be triggered (that is, when reading the directory finishes). That can happen at any time. The calling function, however, doesn't yield the control so example will always finish before any of the callbacks is called.
In one sentence:
All the code of the function/global scope is executed before any callbacks defined in that function/global scope.
In this case, you are calling a function that is doing IO and is asynchronous. That is why you are seeing output the way you are.
Because the rest of your code is executing inline - on the single execution thread, it is completed before the IO events are given a chance to make their way onto the event loop.
I would say expect this behavior, but don't depend on it with absolute certainty as it does depend on the implementation of the library using the callback. An (bad, evil) implementor could be making an synchronous request to see if there is any work to be done and, if not, callback immediately. (Hopefully you'll never see this, but…).
I would like to add a bit to #dc5's answer. On it's website they describe node as
Node.js uses an event-driven, non-blocking I/O model
The event driven part is very significant. It usually clears my doubts when I am having trouble understanding the execution model of the node programs.
So taking your example what is happening is :
Here is printed to the console.
An async call is made to the files.
Node attaches a listener to the async call.
Continues down the execution line and There is printed.
Now it could be that the async call is completed before the current piece of code that is being executed but node js completes the task at hand and then returns to service the async call.
So instead of waiting for anything it keeps on executing in line. Which is why node js execution loop is never idle.

Are JavaScript functions asynchronous?

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
takeInput();
processInput();
outputInput();
Option #2
outputInput();
processInput();
takeInput();
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.
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();
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.
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.
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.
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.

Categories

Resources