Related to the definition

The Javascript language divides the execution modes of the task into two types: Synchronous and Asynchronous.

  1. Synchronization: When a process executes a request that takes a while to return information, the process will wait until it receives the message before continuing.
  2. Asynchronous: the process does not have to wait forever, but continues to perform the following operations, regardless of the state of other processes. When a message is returned, the system notifies the process to process it, which improves the execution efficiency.
  3. Process: Narrowly defined, an instance of a running program. In a broad sense, a process is a running activity of a program with some independent function about a data set. It is the basic unit of dynamic execution of operating system. In traditional operating system, process is both the basic unit of allocation and the basic unit of execution.
  4. Thread: A thread is a single sequence control flow in a program. A relatively independent, schedulable execution unit within a process, which is the basic unit of a system for scheduling and allocating CPUS independently. The scheduling unit of a running program.
  5. Single thread: When a program is executed, the path of the program is arranged in sequential order. The first one must be processed before the next one can be executed. A single thread is a process with only one thread.
  6. Multithreading: The practice of running multiple threads simultaneously to perform different tasks in a single program.

knowledge

Js is single threaded

JS runs in the browser and is single-threaded, one JS thread per window, and since it is single-threaded, only certain code can be executed at any given moment, blocking other code. Whereas browsers are event-driven, a lot of the behavior in browsers is asynchronous, creating events and putting them on execution queues, and JavaScript engines are single-threaded task queues that process them. When asynchronous events occur, mouse click events occur, timer trigger events occur, XMLHttpRequest completion callback fires, and so on, put them in an execution queue and wait for the current code to complete.

Browsers are not single-threaded

Although JS runs in a browser, it is single-threaded, but browsers are not single-threaded, such as a Web Kit engine, may have the following threads:

  • JavaScript engine threads
  • Interface rendering thread
  • The browser event triggers the thread
  • HTTP request thread

When an asynchronous event occurs, it enters the event queue. Browsers have an internal large message Loop, Event Loop, that polls the Event queue and processes the Event. For example, if the browser is currently busy processing the onClick event, the window onSize event occurs, and the asynchronous event is placed in the event queue for processing.

Why is JavaScript single-threaded but AJAX can send and callback requests asynchronously, and why does setTimeout look multithreaded?

Ajax requests are indeed asynchronous; they are requested by a new thread opened by the browser, and the Event callback is placed in the Event Loop single-threaded Event queue waiting to be processed. When the browser is idle and the out-of-queue task is processed, the JavaScript engine always runs the callback function single-thread, single-thread processing its task queue.

SetTimeout (func, 0) This is to tell the JS engine to put the func on the main event queue after 0ms and wait for the current code to finish executing. That’s the magic of it. It has three uses:

  1. Let the browser render the current changes (many browser UI render and JS execution are placed in a thread, thread blocking causes the interface to be unable to update the render)
  2. Recalculate the script runtime, rejudge the warning “script is running too long”
  3. Changed the execution order

See the next article, “Using setTimeout(func, 0)” for more details. # # # # # # # # # # # # # # #

There are three approaches to asynchronous programming

One: callback function

This is the most basic approach to asynchronous programming. Suppose you have two functions f1 and f2, the latter waiting for the result of the former.

f1(); f2();Copy the code

If F1 is a time-consuming task, consider writing F2 as a callback function for F1.

 function f1(callback){ setTimeout(function () {// the task code for f1callback(); },1000); }Copy the code

Executing code looks like this:

f1(f2);Copy the code

In this way, we change the synchronous operation to asynchronous operation, and F1 does not block the program. The advantages of the callback function are that it is simple, easy to understand, and deploy. The disadvantages are that it is not easy to read and maintain the code, the parts are highly coupled, the process can be messy, and only one callback function can be specified per task.

2. Event monitoring

Another approach is to adopt an event-driven model. The execution of tasks depends not on the order of the code, but on whether an event occurs. Again, take F1 and F2. First, bind an event to F1 (written in jQuery).

f1.on('done', f2);Copy the code

The above line of code means that f2 is executed when a done event occurs in F1. Then, rewrite f1:

  function f1(){ setTimeout(function () {// the task code for f1f1.trigger('done'); },1000); }Copy the code

F1.trigger (‘done’) indicates that, immediately after execution, a done event is triggered to start execution of F2. The advantage of this approach is that it is relatively easy to understand, multiple events can be bound, multiple callback functions can be specified for each event, and it can be “decouple”, facilitating modularity. The disadvantage is that the entire program has to be event-driven, and the flow becomes very unclear.

B. Promises

Promise is a solution to asynchronous programming that is more reasonable and powerful than the traditional solutions of “callback functions” and “events.” It was first proposed and implemented by the community, and ES6 has written it into the language standard, unifying usage, and providing Promise objects natively. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way. The basic usage is as follows:

    const promise = new Promise(function(resolve, reject) {
      // ... some code
      if (/* Asynchronous operation succeeded */){
        resolve(value);
      } else{ reject(error); }}); promise.then(function(value) {
    // success
    }, function(error) {
     // failure
    });Copy the code

Here’s another way to write an asynchronous operation that fails and catches an exception

const promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));
});
promise.catch(function(error) {
  console.log(error);
});Copy the code

The advantage of this is that the callback function becomes chained, the flow of the program can be clearly seen, and many powerful functions can be achieved. For example, specify multiple callback functions and so on.