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

A brief introduction to asynchronous execution in JS

Jul 07, 2017 pm 02:57 PM
javascript asynchronous implement

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());
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 A brief introduction to asynchronous execution in JS. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Advanced Guide to Python asyncio: From Beginner to Expert Advanced Guide to Python asyncio: From Beginner to Expert Mar 04, 2024 am 09:43 AM

Concurrent and Asynchronous Programming Concurrent programming deals with multiple tasks executing simultaneously, asynchronous programming is a type of concurrent programming in which tasks do not block threads. asyncio is a library for asynchronous programming in python, which allows programs to perform I/O operations without blocking the main thread. Event loop The core of asyncio is the event loop, which monitors I/O events and schedules corresponding tasks. When a coroutine is ready, the event loop executes it until it waits for I/O operations. It then pauses the coroutine and continues executing other coroutines. Coroutines Coroutines are functions that can pause and resume execution. The asyncdef keyword is used to create coroutines. The coroutine uses the await keyword to wait for the I/O operation to complete. The following basics of asyncio

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

PHP asynchronous coroutine development: speed up data caching and read and write operations PHP asynchronous coroutine development: speed up data caching and read and write operations Dec 18, 2023 pm 01:09 PM

PHP asynchronous coroutine development: accelerating data caching and read and write operations. In actual application development, data caching and read and write operations are common performance bottlenecks. In order to improve system efficiency and user experience, PHP asynchronous coroutine technology can be used to accelerate these operations. This article will introduce the basic concepts and principles of PHP asynchronous coroutines and provide specific code examples. 1. The concept and principle of asynchronous coroutine Asynchronous coroutine is an efficient concurrent programming technology that uses a single thread to achieve lightweight task scheduling and collaboration. Compared with traditional multi-threaded or multi-process concurrent programming

See all articles