Home  >  Article  >  Web Front-end  >  A brief introduction to asynchronous execution in JS

A brief introduction to asynchronous execution in JS

怪我咯
怪我咯Original
2017-07-07 14:57:521044browse

The following editor will bring you a brief discussion on the asynchronous execution of js. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

1.JavascriptThe execution environment of the language is "single thread":

Advantages: It is relatively simple to implement, and the execution environment is relatively simple;

Disadvantages: As long as one task takes a long time, subsequent tasks must be queued up, which will delay the execution of the entire program. Common browser unresponsiveness (suspended death) is often caused by a certain piece of Javascript code running for a long time (such as an infinite loop), causing the entire page to get stuck in this place and other tasks cannot be performed.

In order to solve this problem, the Javascript language divides the task execution mode into two types: synchronous (Synchronous) and asynchronous (Asynchronous).

2. Several methods of "asynchronous mode" programming:

(1)Callback function : The advantage is that it is simple and easy to understand and deploy. The disadvantage is that it is not conducive to reading and maintaining the code. The various parts are highly coupled (Coupling), making the program structure confusing and the process difficult to track (especially Nested callback functions), and only one callback function can be specified for each task.

(2) Adopt event-driven mode (event listening): The advantage is that it is easier to understand, multiple events can be bound, and multiple events can be specified for each event The callback function can be "decoupled" (Decoupling), which is conducive to realizing modularization. The disadvantage is that the entire program must become event-driven, and the running process will become very unclear.

(3)Observer mode(Publish\Subscribe mode):The nature of this method is similar to "event listening", but significantly better than the latter. Because we can monitor the operation of the program by looking at the "Message Center" to see how many signals exist and how many subscribers each signal has.

3. Process control of asynchronous operations.

(1) Serial execution: Write a process control function and let it control asynchronous tasks. After a task is completed, another Execute another one.

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
function series(item) {
 if(item) {
  async( item, function(result) {
   results.push(result);
   return series(items.shift());
  });
 } else {
  return final(results);
 }
}
series(items.shift());

Function series is a serial function. It will execute asynchronous tasks in sequence. The final function will not be executed until all tasks are completed. The items array stores the parameters of each asynchronous task, and the results array stores the running results of each asynchronous task.

(2) Parallel execution: All asynchronous tasks are executed at the same time, and the final function is not executed until all are completed.

//forEach方法会同时发起6个异步任务,等到它们全部完成以后,才会执行final函数。
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];

items.forEach(function(item) {
 async(item, function(result){
  results.push(result);
  if(results.length == items.length) {
   final(results);
  }
 })
});

The advantage of parallel execution is that it is more efficient. Compared with serial execution, which can only execute one task at a time, it saves time. But the problem is that if there are many parallel tasks, it is easy to exhaust system resources and slow down the operation speed. Therefore, there is a third method of process control.

(3) Combination of parallel and serial: Set a threshold, and only n asynchronous tasks can be executed in parallel at most at a time. This avoids excessive use of system resources.

//变量running记录当前正在运行的任务数,只要低于门槛值,就再启动一个新的任务
//如果等于0,就表示所有任务都执行完了,这时就执行final函数
//最多只能同时运行两个异步任务。
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;

function launcher() {
  while(running < limit && items.length > 0) {
    var item = items.shift();
    async(item, function(result) {
      results.push(result);
      running++;
      if(items.length > 0) {
        launcher();
      }
    });
    running--;
    if(running == 0) {
      final();
    }
  }
}

The above is the detailed content of A brief introduction to asynchronous execution in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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