Home > Web Front-end > JS Tutorial > Detailed explanation of javascript asynchronous execution and operation flow control examples

Detailed explanation of javascript asynchronous execution and operation flow control examples

伊谢尔伦
Release: 2017-07-22 11:34:39
Original
1618 people have browsed it

1. The execution environment of Javascript language is "single thread":

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

Disadvantages: As long as there is one task It takes a long time, and 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, easy to understand and deploy, but the disadvantage is that it is not conducive to reading and maintaining the code. Each The high degree of coupling between parts makes the program structure confusing and the process difficult to track (especially when callback functions are nested), 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, multiple callback functions can be specified for each event, and it can be "decoupled" (Decoupling) , which is conducive to modularization. The disadvantage is that the entire program has to become event-driven, and the running process will become very unclear.

(3) Observer pattern (publish\subscribe pattern): The nature of this method is similar to "event listening", but it is obviously 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 one task is completed, another one will be executed.

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());
Copy after login

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);
  }
 })
});
Copy after login

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();
    }
  }
}
Copy after login

The above is the detailed content of Detailed explanation of javascript asynchronous execution and operation flow control examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template