This article talks about javascript Implementing threads and event loops. If you don’t know about javascript’s implementation of threads and event loops, or if you are interested in javascript’s implementation of threads and event loops, let’s take a look. This article, let’s cut the nonsense and get to the point
1. Why is JavaScript said to be single-threaded?
The several threads involved in the browser rendering process are: JavaScript execution thread, responsible for executing js code, UI thread, responsible for UI display ,JavaScript eventLoop thread, manage
Manage JavaScript events, where the JavaScript execution thread and the UI thread are mutually exclusive. If JavaScript is multi-threaded, then When multiple JavaScript execution threads operate the same DOM, such as turning a button red and yellow respectively, the UI thread will be confused. Who should listen? In order to avoid this situation in JavaScript, these
threads must be executed separately, so JavaScript is single-threaded. This has become the core feature of this language and will not be used in the future. will change.
2. JavaScript taskQueue
Structure and event loopkeep waiting.
Execution tasks in JavaScript are executed according to the queue data structure, as shown below:
Tasks in JavaScript:
1. Synchronization tasks:
for loop, summation, js assignment, js operation, etc.##2. Asynchronous tasks: dom events, bom api processing ajax
The so-called "
Callback function" (callback) is the code that will be hung up by the main thread. Asynchronous tasks must specify a callback function. When the main thread starts executing an asynchronous task, executes the corresponding callback function.
Loop mechanism:
The JavaScript main thread directly executes the synchronous task, the asynchronous task executes part of the asynchronous task first, and thenexits The main thread executes, Then wait for the asynchronous task to be ready before handing it over to the main thread for execution.
In short, JavaScript code is executed one by one in the form of a queue, and only one piece of code can be executed at the same time. Related recommendations:
Details of the JavaScript event loop mechanism - Lecture 1
Detailed explanation of JavaScript event loop mechanism - Lecture 2
Detailed explanation of JavaScript event loop mechanism examples
The above is the detailed content of Detailed explanation of JavaScript implementation of threads and event loop. For more information, please follow other related articles on the PHP Chinese website!