Home > Web Front-end > JS Tutorial > Detailed introduction to js thread mechanism and event mechanism (picture and text)

Detailed introduction to js thread mechanism and event mechanism (picture and text)

不言
Release: 2018-10-16 14:08:00
forward
2447 people have browsed it

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.

Detailed introduction to js thread mechanism and event mechanism (picture and text)

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.

Detailed introduction to js thread mechanism and event mechanism (picture and text)Detailed introduction to js thread mechanism and event mechanism (picture and text)

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.

Detailed introduction to js thread mechanism and event mechanism (picture and text)

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

4. What are the advantages and disadvantages of single-threading and multi-threading?

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

2. Browser kernel

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.

1. Different browsers may be different

  • Chrome, Safari: webkit

  • firefox: Gecko

  • IE: Trident

  • ##360, Sogou and other domestic browsers: Trident webkit

2. Kernel Composed of many modules

  • html, css document parsing module: responsible for parsing page text

  • dom/css module: responsible for dom/css in Related processing in memory

  • Layout and rendering module: responsible for page layout and effect drawing

  • Timer module: responsible for timer Management

  • Network request module: responsible for server requests (regular/Ajax)

  • Event response module: responsible for event management

3. Thoughts caused by timers

1. Is the timer really executed at regular intervals?

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()之后')
Copy after login

Detailed introduction to js thread mechanism and event mechanism (picture and text)

There are two points we need to pay attention to:

  • Timer zero delay (setTimeout(func, 0)) does not mean The callback function is executed immediately. The callback function will not be executed until at least 4ms. It depends on whether the main thread is currently idle and the tasks waiting in front of it in the "task queue".

  • Only when the specified time is reached, the timer will insert the corresponding callback function into the end of the "task queue"

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(&#39;number&#39;)
  document.getElementById(&#39;btn&#39;).onclick = function () {
    var number = input.value
    var result = fibonacci(number)
    alert(result)
  }
</script>
Copy after login

Detailed introduction to js thread mechanism and event mechanism (picture and text)

很显然遇到这种页面堵塞情况,很影响用户体验的,有没有啥办法可以改进这种情形?----Web Worker就应运而生了!

Web Worker 的作用,就是为 JavaScript 创造多线程环境,允许主线程创建 Worker 线程,将一些任务分配给后者运行。在主线程运行的同时,Worker 线程在后台运行,两者互不干扰。等到 Worker 线程完成计算任务,再把结果返回给主线程。这样的好处是,一些计算密集型或高延迟的任务,被 Worker 线程负担了,主线程(通常负责 UI 交互)就会很流畅,不会被阻塞或拖慢。其原理图如下:

Detailed introduction to js thread mechanism and event mechanism (picture and text)

2. Web Workers的基本使用

主线程

  • 首先主线程采用new命令,调用Worker()构造函数,新建一个 Worker 线程

var worker = new Worker('work.js');
Copy after login
  • 然后主线程调用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
Copy after login

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>
Copy after login
  • 不能跨域加载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!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template