The call stack

JavaScript is a single-threaded language. That means it can have one call stack at a given time (take one thread = one call stack). Furthermore, it implies that JavaScript cannot do more than two things at a time. Or can it?

When you call a function, you step inside that function. This function is added to the call stack. When the function returns a value, the function is popped from the call stack.

Let's take a look at this example:

const page1 = $.syncHTTP('http://example.com/page1');
const page2 = $.syncHTTP('http://example.com/page2');
const page3 = $.syncHTTP('http://example.com/page3');
const page4 = $.syncHTTP('http://example.com/page4');

console.log(page1, page2, page3, page4);

For the sake of simplicity, consider $.syncHTTP as a predefined method that performs synchronous HTTP requests, that is, it'll block the code until completed. Let's assume every request takes ~500 ms to complete. Thus, if all these requests fire on clicking, say, a button, JavaScript immediately blocks the browser from doing anything for two seconds! That kills the user experience by a factor of 100!

Clearly, the call stack will consist of the first request, then after 500ms it'll remove that from the call stack, go to the second request, add that to the call stack, wait for 500ms for the response to receive, remove that from the call stack, and so on.

However, something strange happens when we make use of an asynchronous function such as setTimeout(). Take a look at this example:

console.log('Start');

setTimeout( () => {
console.log('Middle');
}, 1000 )

console.log('End');

Here, as you expect, we'll first get Start printed because the call stack adds console.log to the stack, executes it, and removes it from the stack. Then the JavaScript comes to setTimeout(), adds it to the call stack, magically removes it without doing anything (more on this later), comes to the final console.log, adds it to the call stack, executes it to show End, and removes it from the stack.

Finally, magically, after 1 second, another console.log appears on the call stack, gets executed to print Middle, and then gets removed from the call stack.

Let's understand this magic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.176.155