Home  >  Article  >  Web Front-end  >  Detailed explanation of JS operating mechanism

Detailed explanation of JS operating mechanism

小云云
小云云Original
2018-03-17 16:04:081780browse

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

  1. GUI rendering thread

  2. JS engine thread

  3. JS event trigger thread

  4. Timed trigger thread

  5. 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.
Detailed explanation of JS operating mechanism
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn