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)