JavaScript single thread and asynchronous details

JavaScript single thread and asynchronous details

Preface:

When it comes to JavaScript 's single threaded and asynchronous nature, many students can't help but wonder, isn't this a contradiction? In fact, single-threaded and asynchronous cannot be the characteristics of a language at the same time. js chose to be a single-threaded language, so it itself cannot be asynchronous, but the host environment of js (such as browsers, Node ) is multi-threaded, and the host environment makes js have asynchronous properties in some way (event-driven, which will be discussed below). Looking down, you will find how simple and efficient the js mechanism is!

Browser:

js is a single-threaded language. The browser only allocates one main thread to js to execute tasks (functions), but only one task can be executed at a time. These tasks form a task queue waiting to be executed. However, some tasks on the front end are very time-consuming, such as network requests, timers, and event monitoring. If they are made to wait in line like other tasks, the execution efficiency will be very low, and even cause the page to freeze. Therefore, the browser opens up additional threads for these time-consuming tasks, mainly including http request threads, browser timing triggers, and browser event trigger threads. These tasks are asynchronous. The following diagram illustrates the main thread of a browser.

1. Task Queue

I just mentioned that the browser opens a separate thread for asynchronous tasks such as network requests, so the question is, how does the main thread know when these asynchronous tasks are completed? The answer is the callback function. The whole program is event-driven, and each event will be bound to a corresponding callback function. For example, there is a piece of code that sets a timer.

setTimeout(function(){
    console.log(time is out);
}, 50);


When this code is executed, the browser performs the timing operation asynchronously. When 50ms is reached, the timing event will be triggered. At this time, the callback function will be placed in the task queue. The entire program is driven by such events.
Therefore, js has always been single-threaded, and the browser is the one that implements asynchrony.

Back to the main thread:

js has been doing one job, which is to extract tasks from the task queue and put them into the main thread for execution. Let’s take a deeper look at this.

Let's match the concepts we just learned with the diagram. The threads that the browser opens up separately for asynchronous tasks mentioned above can be uniformly understood as WebAPIs . The task queue mentioned above is callback queue . The main thread we are talking about is the part composed of dotted lines. The heap and stack together constitute the js main thread. The execution of functions is achieved by pushing and popping the stack. For example, there is a foo() function in the diagram. The main thread pushes it into the stack. When executing the function body, it finds that the above functions need to be executed, so these functions are pushed into the stack again. After the function is executed, the function is popped from the stack. When the stack is empty, it means that a task has been completed. At this time, the next task will be found in callback queue and pushed into the stack ( this search process is called an event loop because it always loops to see if there are any tasks in the task queue ).

2. To explain some confusing issues

1. What is setTimeout(f1,0)?

The biggest question about this statement is, is f1 executed immediately? The answer is not necessarily, because it depends on whether the command in the main thread has been executed, as shown in the following code:

setTimeout(function(){
console.log(1);
},0);
console.log(2);

2. Is the Ajax request asynchronous?

After understanding the above content, we know that ajax requests are asynchronous. When the request is completed, the request completion event will be triggered, and then the callback function will be placed in callback queue . When the main thread executes the callback function, it is still single-threaded.

3. The interface rendering thread is a separate thread

The interface rendering thread is a separately opened thread. Does it mean that the interface will be re-rendered immediately once the DOM changes?

If the interface is re-rendered immediately as soon as the DOM changes, the efficiency will inevitably be very low, so the browser mechanism stipulates that the interface rendering thread and the main thread are mutually exclusive. When the main thread executes tasks, the browser rendering thread is in a suspended state.

3. How to use the browser's asynchronous mechanism

We already know that js has always been executed in a single thread, and the browser has set up separate threads for several obvious time-consuming tasks to solve the time-consuming problems. However, in addition to these obvious time-consuming problems, there may also be time-consuming functions in the programs we write ourselves. How to deal with this situation? We certainly cannot open a separate thread ourselves, but we can use the windows opened by the browser. The browser timer thread and event trigger thread are easy to use, but the network request thread is not suitable for us. Let’s take a closer look:

Assume that the time-consuming function is f1, and f1 is the predecessor task of f2.

Use the timer to trigger the thread:

function f1(callback){
setTimeout(function(){
    // f1 code callback();
},0);
}
f1(f2);

This writing method has a high degree of coupling.

Use events to trigger threads:

$f1.on('custom',f2); //Here the binding event is written as jQuery function f1(){
setTimeout(function(){
    // code for f1$f1.trigger('custom');
},0);
}


This method decouples method one by binding custom events, so that different callback functions can be implemented by binding different events. However, if this method is applied too much, it will be difficult to read the program.

4. Benefits of Asynchrony and Suitable Scenarios

Benefits of asynchrony:

Let's compare synchronization and asynchrony through an example. Suppose there are four tasks (numbered 1, 2, 3, and 4), and their execution time is 10ms. Task 2 is the predecessor task of Task 3, and Task 2 requires a response time of 20ms. Let's make a comparison below, and you will know how to implement non-blocking I/O.

Suitable for:

It can be seen that when our program requires a large number of I/O operations and user requests, js, a language with single-threaded, asynchronous, and event-driven qualities, is very suitable! Compared with multi-threaded languages, it does not have to consume too much system overhead, nor does it have to devote energy to dealing with multi-threaded management. Compared with synchronous execution languages, the asynchronous and event-driven mechanisms of the host environment allow it to achieve non-blocking I/O, so you should know what kind of scenarios it is suitable for!

This is the end of this detailed article about JavaScript single-threaded and asynchronous. For more relevant JavaScript single-threaded and asynchronous content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on the three major issues of JS: asynchrony and single thread
  • Detailed explanation of asynchronous process implementation in single-threaded JavaScript
  • Analyze the characteristics of JS single-threaded asynchronous io callback
  • JavaScript's Three Mountains: Single Thread and Asynchronous

<<:  MySQL 8.0.22 winx64 installation and configuration method graphic tutorial

>>:  Nginx 502 Bad Gateway Error Causes and Solutions

Recommend

MySQL 5.7.20 free installation version configuration method graphic tutorial

I have seen many relevant tutorials on the Intern...

TypeScript enumeration basics and examples

Table of contents Preface What are enums in TypeS...

Best Practices for Implementing Simple Jira Projects with React+TS

A set of projects for training react+ts Although ...

dl, dt, dd list label examples

The dd and dt tags are used for lists. We usually...

Vue data two-way binding implementation method

Table of contents 1. Introduction 2. Code Impleme...

HTML table_Powernode Java Academy

To draw a table in HTML, use the table tag tr me...

mysql5.7.18 decompressed version to start mysql service

The decompressed version of mysql5.7.18 starts th...

Vue basics MVVM, template syntax and data binding

Table of contents 1. Vue Overview Vue official we...

How to use worker_threads to create new threads in nodejs

Introduction As mentioned in the previous article...

CSS float (float, clear) popular explanation and experience sharing

I came into contact with CSS a long time ago, but...

Implementing shopping cart function based on vuex

This article example shares the specific code of ...

Detailed explanation of common methods of Vue development

Table of contents $nextTick() $forceUpdate() $set...

Vue implements card flip carousel display

Vue card flip carousel display, while switching d...

A brief discussion on several ways to pass parameters in react routing

The first parameter passing method is dynamic rou...