The JavaScript engine keeps a call stack (basically a list) of the functions that are running.
When a function is invoked, it is added to the list. When all of the code inside a function has been run, then the function is removed from the call stack.
The cool part about a call stack is that a function doesn't have to complete before another function is added to the call stack. (𝘙𝘦𝘮𝘦𝘮𝘣𝘦𝘳 𝘵𝘩𝘢𝘵, 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵 𝘪𝘴 𝘢 𝘴𝘪𝘯𝘨𝘭𝘦-𝘵𝘩𝘳𝘦𝘢𝘥𝘦𝘥 𝘭𝘢𝘯𝘨𝘶𝘢𝘨𝘦; 𝘪𝘵 𝘤𝘢𝘯 𝘱𝘳𝘰𝘤𝘦𝘴𝘴 𝘰𝘯𝘦 𝘤𝘰𝘮𝘮𝘢𝘯𝘥 𝘢𝘵 𝘢 𝘵𝘪𝘮𝘦).
How it works: https://youtu.be/J9iKeNhoXNM
𝗕𝘂𝘁, that happens if the function was synchronous "occurring at the same time".
What if the function was asynchronous "executed at some later point in time"?
For example: a setTimeout() or .addEventListener() like when you click on a button, a new element added!
How does JavaScript handle that?!!
Where does the function go to wait?
How does the function get run when it needs to?
Answer:
This happens because of the JavaScript 𝙀𝙫𝙚𝙣𝙩 𝙇𝙤𝙤𝙥!
There are three parts you have to think about around the event loop:
The Call Stack
Web APIs/The browser
An Event Queue
So, the asynchronous function is passed to the browser for future use "for example: on click function", the browser will hold that function until there's a click event.
What happens if someone clicks before a current synchronous code is done?
When there is a click event and there is code already running, the callback function on click can't just be added directly to the Call Stack because of JavaScript's run-to-completion nature; we can't interrupt any code that might currently be happening. So the function is placed in the Event Queue. When all of the functions in the Call Stack have finished (also known as idle time), then the Queue is checked to see if anything is waiting. If something is in the Queue, then it's run, creating an entry on the call stack.
In case of a setTimeout()?
It will also be passed to the browser, and after the time of milliseconds that is given, it is moved to the Event Queue (even if that was 0 milliseconds!), then the function is moved to the Call Stack and executed.
IMPORTANT: The key things to remember here are 1) current synchronous code runs to completion, and 2) events are processed when the browser isn't busy. Asynchronous code (such as loading an image) runs outside of this loop and sends an event when it is done.
Walk through an example: https://youtu.be/uBdemYBG-ek
** 𝘒𝘯𝘰𝘸𝘪𝘯𝘨 𝘩𝘰𝘸 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵 𝘢𝘯𝘥 𝘵𝘩𝘦 𝘌𝘷𝘦𝘯𝘵 𝘓𝘰𝘰𝘱 𝘸𝘰𝘳𝘬 𝘤𝘢𝘯 𝘩𝘦𝘭𝘱 𝘶𝘴 𝘸𝘳𝘪𝘵𝘦 𝘤𝘰𝘥𝘦 𝘵𝘩𝘢𝘵 𝘪𝘴 𝘮𝘰𝘳𝘦 𝘦𝘧𝘧𝘪𝘤𝘪𝘦𝘯𝘵.
Credits: Udacity
Top comments (0)