This is the ninth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

EventLoop is an eventLoop designed to coordinate events, user interaction tasks, scripting tasks, rendering tasks, network tasks, etc. Js itself is a single threaded scripting language, there are synchronous and asynchronous mechanisms in the run, it is not like Java can open multiple threads for multi-threaded operations, as far as JS itself, it is not so powerful Java programming language, just a scripting language; So once there are multiple threads, it is necessary to consider the communication between threads and so on, so it becomes complicated; This is one of the reasons why js was originally defined as a single-threaded scripting language. The asynchronous mechanism of JS is composed of eventLoop and Task Queue. The main thread has an execution stack and a queue. When the main thread executes the code of the current execution stack, it will first push the function into the stack, and then exit the stack after the function is run. After the current execution stack is finished, the next task is removed from the queue and the queue is cleared.

The nature of task queues:

All synchronous tasks are executed on the main thread, forming an execution stack;

In addition to the main thread, there is a task queue. Whenever an asynchronous task has run results, an event is placed in the task queue.

Once all the synchronized tasks in the execution stack have been executed, the system reads the task queue to see what events are in it. The corresponding asynchronous tasks then end the wait state, enter the execution stack, and start to execute.

The process for combining macroTask and microtash is as follows:

1. Fetch a macrotash from the task queue and execute it.

2. Check the microtask queue, execute and empty the microtask queue; If in the process of execution, there is a new microtask, put the change to the execution queue, and then execute this step, until the microtask is cleared;

3, perform UI render operation, check whether there is currently a render opportunity and need to render, if so, then start to perform all kinds of render required work, including animation frame callBacks, finally render UI, if not need to directly skip; Then the first step is executed and the round robin is carried out until the task queue is empty.

var taskMacLength = 10; // ----- Task queue
while(taskMacLength > 0) {/ / execution stack
	console.log(This is the number one.,taskMacLength, "A mission");     
	taskMacLength--; 
}; 
console.log('Mission accomplished');
function fn(){        
	var a = 1;        
	setTimeout(function(){            
    var b = 2;            
    console.log('b', b);        
  }, 0)        
  console.log('a', a);    
}    
fn();    
var c = 3;    
console.log('c', c);        // a:1 c:3 b:2
Copy the code

When the main thread executes code, when it encounters a function, it just declares and defines the function, and the browser puts it on the stack, but it doesn’t execute immediately because it just declares the definition; Next, fn() is encountered, and the fn function’s code is compiled from the context, and the execution context and executable code for that function are created; When a setTimeout is encountered during execution, the main thread notifies the browser’s other threads that this callback is thrown into the browser’s event queue (first in, first out), and waits for the main thread’s other synchronization operations to complete, then console.log(‘a’, a) is executed; Then jump out of fn and go down to console.log(‘c’, c); Wait for the main thread to clear, fetch the new task, and run console.log(‘b’, b);

There are three types of event queue: basic event queue, event handle queue and queue to be executed. Each queue contains an event handle pointer, which points to the event handle queue of the event. Whenever communication is required, the program handle and priority of the event corresponding to the event are added to the queue of the pending execution handle of the event according to the required event type by the method driven event.

process

A process, “process,” is an instance of a program that the browser is running; Crudely speaking, it is a single movement of a program with some independent function about a data set. The process is the minimum unit of CPU resource allocation, but also the most basic allocation unit;

Browser processes. For example, chrome processes include the Browser process, GPU process, third-party plug-in process, and rendering process.

The Browser process can also be called the main Browser process, the main function:

1. Responsible for the display of browser interface and the interaction with users;

2. Responsible for the management, creation and destruction of other processes on each page, such as child processes and GPU processes;

3. Draw the memory Bitmap obtained by the rendering process to the user interface;

4. Management of network resources, such as download;

GPU processes are used to process images, including all GPU tasks sent by other processes. The GPU process is divided into different processes that render different parts of the browser window;

Third-party plug-in processes are used to control all used plug-ins, such as Flash; Each type of plug-in corresponds to a process;

Rendering process is mainly used in page rendering, script execution, event processing and so on; The main process creates multiple rendering processes based on the TAB;

Inter-process Communication (IPC) is adopted between processes. IPC is in fact similar to TCP, which is mainly the transmission layer of the network communication; In the network layer transmission, see more, in addition to TCP, and UDP. TCP is a link-oriented approach. Although the insecure and unstable nature of the network determines that no number of handshakes can guarantee the reliability of the connection, the three-way handshake of TCP ensures the reliability of the connection at a minimum. UDP is not connection-oriented. It does not establish a connection with the other party before transmitting data, and does not send a confirmation signal after receiving the data. The sender does not know whether the data will be correctly received, and of course does not need to resend the data.

Socket is a calling interface and does not belong to the category of protocols. Generally, it is used as a encapsulation of TCP protocol. However, when creating a socket, it can specify the transport protocol used. Socket is a request-response format. The server can actively push messages to the client. The Socket connection is a long connection. Theoretically, the client and the server will not disconnect the connection once the connection is established.

thread

Thread (Thread) is the minimum unit of CPU for scheduling operations. In most cases, it is contained within the process and is the actual operating unit of the process. In a process, a thread refers to a single sequential flow of control in a process. A process can have multiple threads concurrently, each thread performing different tasks in parallel, while these threads can also share the resources of the process.

Macro task

The essence of a macro task is a message queue for communication between multiple threads in the browser. In Chrome, each page corresponds to a process, which in turn has multiple threads, such as JS thread, rendering thread, IO thread, network thread, timer thread and so on. Communication between these threads is achieved by adding a postTask to the task queue of the object.

Each thread has its own queue of tasks to which it or other threads can add tasks via postTask. These threads will take tasks from their queue and execute them. Or wake it up when it’s asleep until the set time or when someone postTask.

The following macro tasks can be created: Script, setTimeOut, setInterval, requestAnimationFrame, I/O, UI render, etc.

Micro tasks

A microtask is a queue that actually exists. A microtask belongs to the current thread, not to a postTask from another thread. It’s just delayed, such as promise. then and mutationObserve.

The following microtasks can be created: promise callback, process. NextTick, MutationObserver, etc.