This article describes the synchronization and Asynchronization of JavaScript. For more information, see Figure 1. hand-drawn.
2. Why is JavaScript a single thread (here I will refer to instructor Ruan Yifeng)
The single thread of JavaScript is related to its purpose.
As a Browser Scripting Language, JavaScript is mainly used to interact with users and operate DOM.
This determines that it can only be a single thread, otherwise it will bring a very complicated synchronization problem.
For example, if JavaScript has two threads at the same time, one thread adds content to a DOM node, and the other thread deletes the node, which thread should the browser take as the standard?
Therefore, in order to avoid complexity, JavaScript is a single thread from its birth, which has become the core feature of the language and will not change in the future.
To utilize the computing capability of multi-core CPUs, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the sub-threads are completely controlled by the main thread and cannot operate the DOM.
Therefore, this new standard does not change the nature of JavaScript single-thread.
Portal: Event Loop
3. Where does JavaScript Asynchronization reflect?
For example, in the first figure, the main thread on the left is synchronization, and the event queue on the left (Message Queue) is asynchronous.
Of course, there are many asynchronous methods in JavaScript:
Ajax (XMLHttpRequest) Image Tag, Script Tag, iframe (similar principle) setTimeout/setIntervalCSS3 Transition/AnimationpostMessageWeb WorkersWeb Socketsand more...