The environment where JS runs is a browser. The browser is multi-process. Each Tab page will open an additional process. The process may include the main control process (responsible for the display of the browser, the user's forward and backward behaviors, etc.) , GPU, browser kernel (browser rendering process, responsible for page rendering, script execution, event processing), etc.
Among them, the browser kernel is multi-threaded, including
GUI rendering thread
JS engine thread
JS event trigger thread
Timed trigger thread
Asynchronous HTTP request thread
You can know that JS is single-threaded. The reason why JS is single-threaded is that JS mainly interacts with users and can also operate DOM elements. If it is multi-threaded, one thread can modify a DOM element. When another thread deletes this DOM element, the browser does not know which thread should be used.
Single thread means task queue, so tasks are executed on one thread. , if the previous task is not completed, the following tasks need to wait, which will cause blocking. In order to avoid this situation, JS has an event loop mechanism to deal with it.
Synchronous tasks will be executed directly on the main thread. If you need to perform an asynchronous task, such as needing to initiate an AJAX asynchronous request, the main thread will tell the asynchronous HTTP request thread to let the asynchronous HTTP request thread perform this. AJAX asynchronous request task, when the HTTP request thread completes the task, it will put the execution result in the message queue. When the main thread's synchronization task is completed, it will read the asynchronous task in the message queue and execute the asynchronous task. Callback function, this process is repeated continuously.
Related recommendations:
Events and callback functions of JavaScript running mechanism
The above is the detailed content of Detailed explanation of JS operating mechanism. For more information, please follow other related articles on the PHP Chinese website!