This series will conclude with the following topics:

2. Object advanced 3. Function advanced 4. Event objects and event mechanisms

Part4: event objects and event mechanism. Below is the outline of my paper.

4.1 Synchronous and Asynchronous

Synchronous: You’re doing one thing and you can’t do another at the same time.

Asynchronous: You are doing something that may take a long time and you can do something else while you are waiting.

Like boiling water… During this process, you worry about boiling water and don’t do anything else, just wait until the water boils, and that’s synchronization.

If you think it’s taking too long, do something else first, like sweeping the floor until the water boils. That’s asynchrony.

4.1 Threads and Processes

1. Process: An execution of a program that occupies a unique piece of memory. You can view the process in Windows Task Manager. A process is responsible for providing the environment necessary for a program to run, equivalent to a factory floor.

2. A thread is an independent execution unit within a process. Is the smallest scheduling unit of the CPU. Is a complete flow of program execution. Threads are responsible for executing programs in the process, the equivalent of factory workers.

3. Diagram the relationship between processes, threads, and programs:

4. Processes and threads

  • The application must run on a thread of a process
  • A process has at least one running thread: the main thread. The process is automatically created after it starts
  • It is also possible to run multiple threads in a process at the same time, and we would say that a program is multithreaded
  • Data within a process can be directly shared by multiple threads within it
  • Data between multiple processes cannot be shared directly (because the process allocates independent memory space to it).
  • Thread pool: A container for storing multiple thread objects, which can be reused repeatedly.

5. What is multi-process and multi-thread?

  • Multi-process running: An application can have multiple instances running simultaneously.
  • Multithreading: Multiple threads running at the same time in a process

6. Compare single-threaded vs. multi-threaded?

7. Is JS single threaded or multi-threaded?

  • JS runs in a single thread

    JS is designed for simple operations, such as submitting a form user name and password. When there is no JS, the data will be submitted to the server, so the data processing will be particularly large, first of all, assuming 1000 people registered at the same time, then these requests will be sent to the server, the server load will be very large, and the user experience is not good, may delay the return of request information. This is much easier when done in the browser. As a result, JS was designed to be single-threaded, because it didn’t require much operation. A single thread is fine and doesn’t take up too much memory. Of course, it will be explained later, because its functionality (DOM manipulation, etc.) also makes it single-threaded.

  • But with Web Workers in H5, you can run multiple threads (the main thread is only one, you can start the thread to do other things).

8. Does the browser run single-process or multi-process?

  • Some are single processes
    • Firefox (Mozilla says Firefox 54 will now be able to split open web tabs into up to four processes to improve browser utilization on PC hardware.)
    • Original IE
  • There are multiple processes
    • chrome
    • A new version of IE

9. How do I check if the browser is running multi-process?

  • Task Manager ==> process

10. Does the browser run single-threaded or multi-threaded?

  • It’s all multithreaded

4.2 Browser Core

Browser kernel: The core program that supports the browser.

4.2.1 Different browsers may have different cores

  • Chrome, Safari : webkitThe kernel
  • Firefox : GeckoThe kernel
  • IE : TridentThe kernel
  • 360, Sogou and other domestic browser:Trident + webkit(Double core, hee hee, give you a look ~)

The browser kernel consists of many modules

  • The main thread

    • JS engine module: responsible for compiling and running JS programs (also code, is to interpret the code we write)
    • HTML,CSS document parsing module: Responsible for page text parsing (initially HTML and CSS text information)
    • DOM/CSS module: Is responsible for DOM/CSS related processing in memory (turning some tags into DOM tree objects)
    • Layout and rendering module: responsible for drawing the layout and effect of the page (refer to the object data in memory for layout and rendering)
  • Points thread

    • Timer module: Manages timers
    • DOM event module: responsible for event management (onclick..)
    • Web request module: Responsible for Ajax requests

4.3 JS thread

1. How to prove that JS execution is single threaded?

  • setTimeout()Is executed on the main thread
  • The timer callback function can only be executed after all the code in the run stack has been executed

2. Why js uses single-threaded mode instead of multi-threaded mode?

  • The single thread of JavaScript, relative to its purpose.
  • As a browser scripting language, JavaScript’s primary purpose is to interact with users and manipulate the DOM.
  • If in a p object (p tag), let’s say in a multi-threaded environment, then there will be thread switching, when one operation is to modify the contents of p, the other is to delete the P tag, this time there will be a conflict.
  • This means that it has to be single-threaded, which can cause complex synchronization problems.

3. Classification of codes:

  • Initialization code (synchronization code)
  • Callback code (asynchronous code)

4. The JS engine performs the basic flow of code

  • Initialize code first: contains some special code
    • Set timer
    • Bind event listener
    • Sending ajax Requests
  • The callback code will be executed at some point later: the callback function (asynchronously executed)
<script type="text/javascript"> setTimeout(function () { console.log('timeout 2222') }, 2000) setTimeout(function () { console.log('timeout 1111') }, 1000) function fn () {the console. The log (' fn () ')} fn () the console. The log (' alert before () ') alert (' -- -- -- -- -- - ') / / suspend execution of the current main thread, and at the same time to suspend the timer timing, Click OK to resume program execution and timing. Console. log('alert() after ') </script>Copy the code

Js is executed by a single thread (the callback function is also in the main thread) 6.H5 proposes a solution to achieve multi-threading: Web Workers 7. Only main thread update interface

4.4 Timer Faults

1. Is the timer executed regularly?

  • Timers are no guarantee of true timing
  • There is usually a slight delay (acceptable), but there may be a long delay (unacceptable)

2. Is the timer callback executed in threading?

  • In the main thread, JS is single threaded. Both callback and non-callback functions are executed on the main thread.

3. How is the timer implemented?

  • Event loop model (covered later)
<button id=" BTN "> Start timer </button> <script type="text/javascript"> document.getelementById (' BTN '). Onclick = function () { Var start = date.now () console.log(' before starting timer... ') setTimeout(function () {console.log(' timer executed ', date.now ()-start)}, 200) console.log(' Timer started... For (var I = 0; i < 1000000000; i++) { } } </script>Copy the code

4.5 Browser event loop (polling) model

4.5.1 Some brief descriptions

  • Code classification
    • Initialization execution code: Some synchronized code, including bindingsdomEvent monitor, set timer, sendajaxRequested code
    • Callback execution code: Code that handles callback logic, asynchronous (binding)domEvent monitor, set timer, sendajaxThe respective callback functions requested.
  • The basic flow of code executed by the JS engine:
    • Initialization code is executed ===> followed by callback code
  • There are two important components of the model:
    • Event (timer /DOM event /AJAX) management module
    • Callback queue: Callback functions waiting to be processed.
  • The flow of the model
    • Execute the initialization code, handing the event callback function to the corresponding module to manage
    • When an event occurs, the management module adds the callback function and its data to the callback queue
    • The callback function execution in the read-fetch callback queue is traversed only after the initialization code has finished executing (which may take some time)

4.5.2 Model schematic diagram

The following diagram is an Event-driven Interaction Model.

Another simple example is the request-Response model (event response model), which is a process in which the browser requests some data to the server, the server receives the request, processes the request, and then returns the request data to the browser, and the browser receives the data and parses it to the page.

Now we mainly look at the Event-driven interaction model:

First, the diagram is divided into three parts: the main thread such as the JS engine, the threading of the browser kernel, and the task queue.

In part I :(heap memory and stack memory)

  • Execution Stack
    • All code is executed in this space
    • Each task is pushed to the “execution stack” one by one in the order defined in the document. The next task is executed only after the current task is completed.
    • Instead, the context object is pushed and popped, and some initialization code is performed, including code to bind dom event listeners, set timers, and send Ajax requests.
    • The event (timer /DOM event /AJAX) callback functions are managed by the corresponding module. Using setTimeout as a comparison, it assigns the callback function and delay time 1000 to the setTimeout module of WebAPIS. This part is not executed in the main process, but in the browser threading.
  • Heap is used to store declared objects.

In Part 2: This piece is mainly handed over to the browser for threading. In comparison to setTimeout timers, he gets the callback function and a delay of 1000, and pushes the callback function to the queue when the delay expires.

In part III:

  • The callback function is temporarily stored, and when the stack is empty, its callback function is pushed onto the stack in turn.

  • This part is called the callback Queue. Also called task queue, Message queue, or event queue. They all mean the same thing.

This process was just introduced with timers. Let’s take an AJAX example and see how you can do this, okay?

The example above shows an asynchronous AJAX request. After an asynchronous task is initiated, the AJAX thread performs time-consuming asynchronous operations, while the JS engine thread continues to perform other synchronous tasks in the heap until all asynchronous tasks in the heap are completed. The messages are then pulled out of the message queue in sequence and executed as a synchronous task in the JS engine thread, and the AJAX callback function is called to execute at some point.

Another point we see in the event mechanism model diagram is event loop, which loops callback functions from the task queue into the execution stack for processing (one after another). The JS engine thread is used to perform synchronization tasks in the stack (initialization code). When all synchronization tasks (initialization code) are completed, the stack is emptied, and then a pending task in the message queue is read, and the related callback function is pushed onto the stack. The single thread starts to execute the new synchronization task. The JS engine thread reads tasks from the message queue in a continuous loop. Every time the stack is cleared, it will read new tasks in the message queue. If there is no new task, it will wait until there is a new task, which is called event polling.

4.5.3 Macro and micro tasks,

Macro task queue

  1. There can be multiple macro task queues
  2. setTimeout
  3. When the macro task queue completes, all tasks in the microtask queue will be executed immediately

Microtask queue

  1. There is only one microtask queue
  2. promiseThe successful callback of the objectprogress.nextTick()
  3. New macro task queues are executed again (if any)
function fun() {
  console.log('Program running'.11111111);
  setTimeout(function () {
    console.log('Timer started'.666666);
  }, 0)
  new Promise(function (resolve, reject) {
    console.log('The Promise object starts executing'.2222222);
    for (var i = 0; i < 5; i++) {
      console.log(i, 33333333);
    }
    resolve();
  })
    .then((a)= > {
      console.log('Successful callback execution of promise object'.555555);
    })
.then((a)= > {
    console.log('Failed callback execution of promise object'.555555);
  });
  console.log('Program completed'.444444444444);
}
fun();
// The sequence structure of the above program is the number 123456.
Copy the code

4.6 the H5 Web Workers

4.6.1 introduction

Web Workers is a javascript multithreading solution provided by HTML5. We can hand over some large computational code to The Web Worker to run without freezing the user interface, but the child thread is completely controlled by the main thread and cannot operate DOM. So, this new standard doesn’t change the single-threaded nature of JavaScript.

4.6.2 Case introduction

Implement a Fibonacci sequence, input the value of the sequence item in the page input, get the corresponding sequence value.

<input type="text" placeholder=" placeholder "ID ="number"> <button id=" BTN ">  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); // The main thread will always handle this recursive call. It freezes the user interface, which means you can't manipulate it. alert(result) } </script>Copy the code

The above operations will be in the main thread of the JS engine, in the process of calculation, will freeze the user interface, to achieve poor user experience.

4.6.3 Using Web Workers

  • The H5 specification provides an implementation of JS threading, named Web Workers. It supports JavaScript multithreaded operations.

  • The relevant API

    • WorkerConstructor to load a thread-based js file
    • Worker.prototype.onmessage: callback function used to receive another thread
    • Worker.prototype.postMessage: Sends a message to another thread
  • Use step 1: Create the JS file to execute in the split thread

  / / workers. Js file

  function fibonacci(n) {
    return n<=2 ? 1 : fibonacci(n- 1) + fibonacci(n2 -)  // recursive call
  }

  console.log(this)
  // When data is received from the main thread
  this.onmessage = function (event) {
    var number = event.data
    console.log('Thread receives data from main thread:'+number)
    // Computations (purpose: to allow complex, time-consuming operations to be processed in threads)
    var result = fibonacci(number)
    postMessage(result) // It is possible to use this method directly because it exists in global objects
    console.log('Thread returns data to main thread:'+result)
    // alert(result) Alert is a window method that cannot be called in thread splitting.
    // The global object in the split thread is no longer window, so it is not possible to update the interface in the split thread
  }
Copy the code

Step 2: Send a message in the JS of the main thread and set the callback

// mainline <input type="text" placeholder=" value "ID ="number"> <button id=" BTN" input = document.getElementById('number') document.getElementById('btn').onclick = function () { var number = Var Worker = new Worker('worker.js') // Bind the listener that receives the message (this position is interchangeable with the location of the code that sends the message to the thread) worker.onMessage = Function (event) {console.log(' the main thread receives data from the sub-thread: '+event.data) alert(event.data)} worker.postMessage(number) console.log(' The main thread sends data to the thread: '+number) } // console.log(this) // window </script>Copy the code

Looking back at the introduction of the 4.6.2 case, we saw that it operated entirely in the main thread, which had the disadvantage of freezing the user interface. In this case, the user interface will not be frozen, but the child thread is completely controlled by the main thread, and the child thread cannot operate DOM, because its this is not window.

4.6.4 diagram

Deficiency 4.6.5

  1. Slow (used to be faster in the main thread, but will be slower in the split thread)
  2. JS cannot be loaded across domains
  3. Worker code cannot access THE DOM(update UI) (because this is not a window)
  4. Not every browser supports this new feature

4.7 Exercises and Cases

Case 1

console.log("1");

setTimeout(function(){
	console.log("2");
},1000);

console.log("3");

setTimeout(function(){
	console.log("4");
},0);
Copy the code

Output: 1->3->4->2.

Case 1 Analysis:

  1. Both console.log() are synchronized, pushing documents into the “execution stack” in order.
  2. The synchronization task in the execution stack is complete.
  3. Push two asynchronous tasks (timers) into the “task queue” in the order of the second parameter (time to delay execution).
  4. Perform asynchronous tasks.

Case 2

Code1 / / synchronization
var t = true;

Asynchronous code2 / /
window.setTimeout(function (){
    t = false;
},1000);

/ / synchronize code2
while (t){}

/ / synchronize code3
alert('end');
Copy the code

Case 2 Analysis:

  1. To perform firstSynchronous code1 -> Synchronous code2.
  2. Now to proceedSynchronous code2whenwhile(true){}, which means that the synchronous code in the stack will never finish executing, so the stack will never be emptied, and the code in the task queue will not execute. That is, asynchronous code in the task queue cannot be executed.

Case 3

// Only when the user triggers a click will the event be pushed into the queue (if the click time is less than the timer specified, the event will be pushed before the timer, otherwise vice versa)
document.querySelector("#box").onclick = function(){
  console.log("click");
};
// The first one to be pushed into the queue
setTimeout(function(){
  console.log("1");
},0);
// The third one is pushed into the queue
setTimeout(function(){
 console.log("2");
},1000);
// The second one is pushed into the queue
setTimeout(function(){
  console.log("3");
},0);
Copy the code

Execution results: such as the analysis in the code snippet above.

Case 3 Analysis:

This is all asynchronous code, including the onclick one. Make sure you know which code is asynchronous. Callbacks in asynchronous code are defined in the heap, that is, they are allocated a chunk of memory on the right side of the heap, and their callbacks are queued for execution according to the time they specify.

The function of setTimeout is to insert the callback function into the message queue after a certain interval of time, and execute it after all synchronization tasks in the stack are completed. Because synchronization tasks in the stack also take time, the interval is generally greater than or equal to the specified time (the specified time is the millisecond value of the argument following the callback function).

SetTimeout (fn, 0) means to insert the callback function fn into the message queue immediately and wait for execution, rather than immediately. Wait for the synchronization task to complete, and then the JS engine (JS virtual machine) takes it out of the task queue to execute it.

Case 4

setTimeout(function() {
    console.log("a")},0)

for(let i=0; i<10000; i++) {}
console.log("b")
Copy the code

Result: B is displayed, and then A is displayed

Case 4 Analysis:

This is pretty close to case 3. Start by executing the synchronization code for the for loop. Timer is asynchronous code, such as the completion of the synchronization of the thread after the completion of the task queue to take these asynchronous code segments to execute.

Example 5: Execute the following code. After executing, click twice within 5s, and click again twice after a period of time (>5s). What is the output of the whole process?

// Asynchronous code
setTimeout(function(){
    for(var i = 0; i < 100000000; i++){}
    console.log('timer a');
}, 0)
// Synchronize the code
for(var j = 0; j < 5; j++){
    console.log(j);
}
// Asynchronous code
setTimeout(function(){
    console.log('timer b');
}, 0)
/ / function
function waitFiveSeconds(){
    var now = (new Date()).getTime();
    while(((new Date()).getTime() - now) < 5000) {}console.log('finished waiting');
}
// Asynchronous code
document.addEventListener('click'.function(){
    console.log('click');
})
// Synchronize the code
console.log('click begin');
// Synchronize code, call function, execute function body
waitFiveSeconds();
Copy the code

Case 5: Perform the synchronization task first. WaitFiveSeconds is a time-consuming operation, which lasts for up to 5s.

0
1
2
3
4
click begin
finished waiting
Copy the code

Then, when the JS engine thread executes, the callback from timer A, the callback from timer B, and the callback from click are placed in the message queue. When the JS engine thread is idle, it checks whether there are any events to execute before processing other asynchronous tasks. This results in the following output order.

click
click
timer a
timer b
Copy the code

Finally, the two click events after 5s are put into the message queue and executed immediately since the JS engine thread is free.

click
click
Copy the code

Case 6

<script> for (var i = 0; i < 5; i++){ var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function (){ console.log(i); }); document.body.appendChild(btn); } // 1. Click Button 4 to output what on the console. 5.*/ / 2. Give an expected implementation /* to change the var in the for loop to let or object. Property holds the value of I */ </script>Copy the code



This document is original by Lv Ya and can be reproduced at will, but please keep the original link and indicate the source.

This article is only published on CSDN and nuggets as of first time:

CSDN home page: https://blog.csdn.net/LY_code

The nuggets homepage: https://juejin.cn/user/3667626521532855

If there are mistakes, timely mention, learn together, progress together. thank you 😝 😝 😝