Home > Article > Web Front-end > Detailed introduction to js thread mechanism and event mechanism (picture and text)
This article brings you a detailed introduction (pictures and texts) about the js thread mechanism and event mechanism. It has a certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.
1. Processes and threads
1. Process
A process refers to an execution of a program, which occupies a unique memory space. You can view the process through the Windows Task Manager (as shown below). At the same time, the same computer system allows two or more processes to be in parallel state, which is multi-process. For example, a computer can run WeChat, QQ, and various browsers at the same time. Some browsers run in a single process, such as firefox and the old version of IE, and some run in multiple processes, such as chrome and the new version of IE.
2. Thread
Some processes can do more than one thing at the same time, such as Word, which can be done at the same time Things like typing, spell checking, printing, and more. Within a process, if you want to do multiple things at the same time, you need to run multiple "subtasks" at the same time. We call these "subtasks" within the process threads.
Thread refers to the basic scheduling unit of the CPU, a complete process of program execution, and an independent execution unit within the process. Multithreading refers to having multiple threads running at the same time within a process. The browser runs multi-threaded. For example, you can use a browser to download, listen to songs, and watch videos at the same time. In addition, we need to know that a major feature of JavaScript language is single-thread. In order to utilize the computing power of multi-core CPU, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but child threads are completely subject to The main thread controls and must not manipulate the DOM. Therefore, this new standard does not change the single-threaded nature of JavaScript.
Since each process has to do at least one thing, a process has at least one thread. Of course, a complex process like Word can have multiple threads, and multiple threads can be executed at the same time. The execution method of multi-threading is the same as that of multiple processes. The operating system also quickly switches between multiple threads, allowing each The threads all alternately run briefly and appear to be executing simultaneously. Of course, truly executing multiple threads simultaneously requires a multi-core CPU to be possible.
3. Processes and threads
The application must run on a thread of a certain process
A process There is at least one running thread in the process: the main thread, which is automatically created after the process is started.
If multiple threads are running at the same time in a process, then the program is multi-threaded.
The memory space of a process is shared, and each thread can use these shared memories.
Data between multiple processes cannot be shared directly
Advantages of single thread: Sequential programming is simple and easy to understand
Disadvantage of single thread: Low efficiency
Multi-threaded Advantages: Can effectively improve CPU utilization
Disadvantages of multi-threading:
The overhead of creating multi-threads
Switching overhead between threads
Deadlock and state synchronization issues
The kernel of the browser refers to the core program that supports the operation of the browser. It is divided into two parts, one is the rendering engine and the other is the JS engine. Now the JS engine is relatively independent, and the kernel is more inclined to talk about the rendering engine.
Chrome, Safari: webkit
firefox: Gecko
IE: Trident
Let’s look at an example first to see if the timer will ensure Execute after 200ms?
document.getElementById('btn').onclick = function () { var start = Date.now() console.log('启动定时器前...') setTimeout(function () { console.log('定时器执行了', Date.now() - start) }, 200) console.log('启动定时器后...') // 做一个长时间的工作 for (var i = 0; i <p style="text-align: center;"><span class="img-wrap"><img src="https://img.php.cn//upload/image/139/417/140/1539669885863938.png" title="1539669885863938.png" alt="Detailed introduction to js thread mechanism and event mechanism (picture and text)"></span><br>In fact, the timer is not executed until 625ms have passed. The timer does not guarantee real timing execution. It will usually be delayed a little bit, or it may be delayed for a long time (such as the above example)</p><p><strong>2. Is the timer callback function executed in separate threads? </strong></p><p><strong>The timer callback function is executed on the main thread. The specific implementation method will be introduced below. </strong></p><p>4. Browser event loop (polling) model<strong></strong></p><p>1. Why JavaScript is single-threaded<strong></strong></p><p>One of the major features of JavaScript language is single-threading, that is to say, only one thing can be done at the same time<strong>. So why can't JavaScript have multiple threads? This can improve efficiency. </strong></p>The single thread of JavaScript is related to its purpose. As a browser scripting language, JavaScript's main purpose 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? <p></p>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. <p>In order to take advantage of the computing power of multi-core CPUs, <br>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<strong>. Therefore, this new standard does not change the single-threaded nature of JavaScript. </strong></p><p>2.Event Loop<strong></strong></p>All tasks in JavaScript can be divided into two types, one is synchronous tasks, and the other is asynchronous tasks (such as various browser events , timer and Ajax, etc.). <p> Synchronous tasks refer to tasks queued for execution on the main thread. The next task can only be executed after the previous task is executed; asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue" (task queue). queue), only when the "task queue" notifies the main thread that an asynchronous task can be executed, will the task enter the main thread for execution<strong>. </strong></p>Specifically, the operating mechanism of asynchronous execution is as follows. (The same is true for synchronous execution, because it can be regarded as asynchronous execution without asynchronous tasks.) <p></p>(1) All synchronous tasks are executed on the main thread, forming an execution context stack. <p></p>(2) In addition to the main thread, there is also a "task queue". As long as the asynchronous task has running results, an event is placed in the "task queue". <p></p>(3) Once all synchronization tasks in the "execution stack" are completed, the system will read the "task queue" to see what events are in it. Those corresponding asynchronous tasks end the waiting state, enter the execution stack, and start execution. <p></p>(4) The main thread keeps repeating the third step above<p></p><p>The main thread reads events from the "task queue". This process is cyclic, so the entire process This operating mechanism is also called Event Loop <strong></strong></p><p style="max-width:90%"><span class="img-wrap"><img src="https://img.php.cn//upload/image/280/170/433/1539669867171806.png" title="1539669867171806.png" alt="Detailed introduction to js thread mechanism and event mechanism (picture and text)"></span>The following example illustrates the event loop very well: <br></p><pre class="brush:php;toolbar:false"> setTimeout(function () { console.log('timeout 2222') alert('22222222') }, 2000) setTimeout(function () { console.log('timeout 1111') alert('1111111') }, 1000) setTimeout(function () { console.log('timeout() 00000') }, 0)//当指定的值小于 4 毫秒,则增加到 4ms(4ms 是 HTML5 标准指定的,对于 2010 年及之前的浏览器则是 10ms) function fn() { console.log('fn()') } fn() console.log('alert()之前') alert('------') //暂停当前主线程的执行, 同时暂停计时, 点击确定后, 恢复程序执行和计时 console.log('alert()之后')
There are two points we need to pay attention to:
Summary: Asynchronous tasks (various browser events, timers, Ajax, etc.) are first added to the "task queue" (when the timer reaches its specified parameters). When the Stack stack (JavaScript main thread) is empty, the first task (queue head) of the Queue queue (task queue) will be read, and will be executed at the end.
5. H5 Web Workers (multi-threading)
1. The role of Web Workers
As mentioned above , JavaScript is single-threaded. When a page loads a js file with complex operations, the user interface may briefly "freeze" and no other operations can be performed. For example, the following example:<input> <button>计算</button> <script> // 1 1 2 3 5 8 f(n) = f(n-1) + f(n-2) function fibonacci(n) { return n<=2 ? 1 : fibonacci(n-1) + fibonacci(n-2) //递归调用 } var input = document.getElementById('number') document.getElementById('btn').onclick = function () { var number = input.value var result = fibonacci(number) alert(result) } </script>
很显然遇到这种页面堵塞情况,很影响用户体验的,有没有啥办法可以改进这种情形?----Web Worker就应运而生了!
Web Worker 的作用,就是为 JavaScript 创造多线程环境,允许主线程创建 Worker 线程,将一些任务分配给后者运行。在主线程运行的同时,Worker 线程在后台运行,两者互不干扰。等到 Worker 线程完成计算任务,再把结果返回给主线程。这样的好处是,一些计算密集型或高延迟的任务,被 Worker 线程负担了,主线程(通常负责 UI 交互)就会很流畅,不会被阻塞或拖慢。其原理图如下:
主线程
首先主线程采用new命令,调用Worker()构造函数,新建一个 Worker 线程
var worker = new Worker('work.js');
然后主线程调用worker.postMessage()方法,向 Worker 发消息。
接着,主线程通过worker.onmessage指定监听函数,接收子线程发回来的消息。
var input = document.getElementById('number') document.getElementById('btn').onclick = function () { var number = input.value //创建一个Worker对象 var worker = new Worker('worker.js') // 绑定接收消息的监听 worker.onmessage = function (event) { console.log('主线程接收分线程返回的数据: '+event.data) alert(event.data) } // 向分线程发送消息 worker.postMessage(number) console.log('主线程向分线程发送数据: '+number) } console.log(this) // window
Worker 线程
Worker 线程内部需要有一个监听函数,监听message事件。
通过 postMessage(data) 方法来向主线程发送数据。
//worker.js文件 function fibonacci(n) { return n<p>这样当分线程在计算时,用户界面还可以操作,而且更早拿到计算后数据,响应速度更快了。</p><p style="text-align: center;"><img src="https://img.php.cn//upload/image/673/101/817/1539670027106347.gif" title="1539670027106347.gif" alt="Detailed introduction to js thread mechanism and event mechanism (picture and text)"><span class="img-wrap"></span></p><p><strong>3. Web Workers的缺点</strong></p>
不能跨域加载JS
worker内代码不能访问DOM(更新UI)
不是每个浏览器都支持这个新特性(本文例子只能在Firefox浏览器上运行,chrome不支持)
The above is the detailed content of Detailed introduction to js thread mechanism and event mechanism (picture and text). For more information, please follow other related articles on the PHP Chinese website!