---
# System prepended metadata

title: Enchi's JS Note - event loop
tags: [JS note]

---

# Enchi's JS Note - event loop


Imagine that JS's operation is a laundry machine. It can wash a piece of clothing at a time. Now, you bring a basket of clothes await washing. Unfortunately, you find that a guy occupied the laundry machine, and he had a huge basket full of clothes. 

**The laundry is "*call stack*". The guy's name is "*blocking*" and the waiting queue formed in fornt of the laundry machine is "*callback queue*"**

So, how to solve this problem? No one wants to wait that long...
One of the solution is **asynchronous callbacks**!!

In JS runtime, it can do one thing at a time, but we can actually do multiple tasks concurrently in the browser. That's due to other APIs in the browser, and those APIs will send back the results when the work is done.

For example, if we call the function setTimeout, it will first land in the browser API. When the work in the browser API ends, it goes to the callback queue, and then waiting to be moved by the event loop to the call stack.

With the help of other APIs, multiple tasks can occur in the browser at the same time. However, if the functions in the call stack consume lots of time to complete, all the tasks in the callback queue will still be blocked.

Thus, to ensure fluent user experience, we should always be careful of the position we put functions with lengthy process. 

* **basic terms memo**
    * **Single threaded**: JS is a single threaded programming language, which means it has only one *call stack*, and can manage one thing at a time
    * **Call stack**: A data structure records our operations in a program by popping in & out functions.
    * **Blocking**: a term used when we must wait a plenty of time for some functions finishing operating
    * **Asynchronous callback:** functions which can operate concurrently.
    * **Event loop**: when the call stack is empty, event loop will check if there's any function in the callback queue, and then move those functions to the call stack.

###### tags: `JS note`