Event Loop
Have you ever encountered the following scenarios, why setTimeout will be executed after Promise? It is obvious that the code is written before Promise. This actually involves knowledge of Event Loop. In this chapter, we will learn more about Event Loop and know the principle of JS asynchronous code execution.
Process and thread
I believe you will often hear that JS is executed in a single thread, but have you ever wondered what a thread is? Speaking of threads, we must also talk about processes. Essentially, both terms are a description of the CPU working time slice. The process describes the time required for the CPU to execute instructions and load and save the context, and it represents a program on the application. A thread is a smaller unit in a process that describes the time required to execute an instruction. Take these concepts to the browser, when you open a Tab page, you actually create a process. A process can have multiple threads, such as a rendering thread, a JS engine thread, an HTTP request thread, and so on. When you initiate a request, you actually create a thread. When the request ends, the thread may be destroyed. As mentioned above, the JS engine thread and the rendering thread, everyone should know that UI rendering may be blocked when JS is running, which shows that the two threads are mutually exclusive. The reason for this is because JS can modify the DOM. If the UI thread is still working when JS is executed, it may cause the UI to be rendered unsafe. This is actually a single-threaded benefit, thanks to the fact that JS is single-threaded, which can save memory, save context switching time, and have the benefits of no lock issues. Of course, the first two points are easier to reflect on the server. For the lock problem, the image is that when I read a number 15, there are two operations to add and subtract the number at the same time, and the result appears at this time mistake. It is not difficult to solve this problem. You only need to add a lock when reading, and write operations cannot be performed until the reading is completed.
Execution stack
The execution stack can be regarded as a stack structure storing function calls, following the principle of first in, last out.
When the JS code is executed, a main function will be executed first, and then our code will be executed. According to the principle of first-in-last-out, the function executed later will be popped out of the stack first. In the figure, we can also find that the function foo is executed later and popped out of the stack when the execution is complete. Usually in development, you can also find traces of the execution stack in the error report
function foo() {
throw new Error('error')
}
function bar() {
foo()
}
bar()
You can clearly see in the above figure that the error is reported in the foo function, and the foo function is called in the bar function.