Home >Web Front-end >JS Tutorial >Briefly talk about synchronization and asynchronousness of JavaScript_javascript skills
1. Draw a picture by hand to illustrate.
2. Why JavaScript is single-threaded (here is a quote from teacher Ruan Yifeng)
JavaScript’s single thread is related to its purpose.
As a browser scripting language, the main purpose of JavaScript is to interact with users and manipulate the DOM.
This determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems.
For example, suppose JavaScript has two threads at the same time. One thread adds content to a certain DOM node, and the other thread deletes the node. In this case, which thread should the browser use?
So, in order to avoid complexity, JavaScript has been single-threaded since its birth. This has become the core feature of this language and will not change in the future.
In order to take advantage of the computing power of multi-core CPUs, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not operate the DOM.
So, this new standard does not change the single-threaded nature of JavaScript.
Portal: Detailed explanation of the Event Loop of JavaScript operating mechanism
3. Where is the asynchronous nature of JavaScript
As shown in the picture at the beginning, I personally think that the main thread on the left is synchronous, and the event queue (message queue) on the left is asynchronous.
Of course there are many asyncs in JavaScript:
Ajax(XMLHttpRequest) Image Tag,Script Tag,iframe(原理类似) setTimeout/setInterval CSS3 Transition/Animation postMessage Web Workers Web Sockets and more…