Home Web Front-end JS Tutorial Detailed explanation of JS queue functions and asynchronous execution examples

Detailed explanation of JS queue functions and asynchronous execution examples

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

This article mainly introduces the relevant information of JavaScriptqueue function and asynchronous execution in detail. It has certain reference value. Interested friends can refer to it

Edit Note: I saw a similar queue function when reviewing other people's JavaScript code, but I didn't understand it. It turns out that this is to ensure that the functions are called in order. After reading this article, I found that it can also be used for asynchronous execution, etc.

Suppose you have several functions fn1, fn2 and fn3 that need to be called in sequence. The simplest way is of course:

fn1();
fn2();
fn3();
Copy after login

But sometimes these functions are added one by one during runtime. When calling, you don’t know what functions there are; at this time, you can pre-define an array, push the functions into it when adding functions, and take them out from the array one by one in order when needed, and call them in sequence:

var stack = [];
// 执行其他操作,定义fn1
stack.push(fn1);
// 执行其他操作,定义fn2、fn3
stack.push(fn2, fn3);
// 调用的时候
stack.forEach(function(fn) { fn() });
Copy after login

It doesn’t matter whether the function has a name or not. You can just pass in the anonymous function directly. Let’s test it:

var stack = [];
function fn1() {
  console.log('第一个调用');
}
stack.push(fn1);

function fn2() {
  console.log('第二个调用');
}
stack.push(fn2, function() { console.log('第三个调用') });

stack.forEach(function(fn) { fn() }); // 按顺序输出'第一个调用'、'第二个调用'、'第三个调用'
Copy after login

This implementation works fine so far, but we have ignored one situation, which is the call of asynchronous functions. Asynchrony is an unavoidable topic in JavaScript. I am not going to discuss the various terms and concepts related to asynchronous in JavaScript here. Readers are asked to check it out by themselves (such as a famous commentary). If you know that the following code will output 1, 3, and 2, then please continue reading:

console.log(1);

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

console.log(3);
Copy after login

If there is a function in the stack queue that is a similar asynchronous function, our implementation will be messed up:

var stack = [];

function fn1() { console.log('第一个调用') };
stack.push(fn1);

function fn2() {
  setTimeout(function fn2Timeout() {
     console.log('第二个调用');
  }, 0);
}
stack.push(fn2, function() { console.log('第三个调用') });

stack.forEach(function(fn) { fn() }); // 输出'第一个调用'、'第三个调用'、'第二个调用'
Copy after login

The problem is obvious, fn2 is indeed called in sequence, but the function fn2Timeout() { console.log('second call') } in setTimeout is not executed immediately (even if timeout is set to 0) ; Return immediately after fn2 is called, and then execute fn3. After fn3 is executed, it is really fn2Timeout's turn.

How to deal with it? After our analysis, the key here is fn2Timeout. We must wait until it is actually executed before calling fn3. Ideally, it looks like this:

function fn2() {
  setTimeout(function() {
    fn2Timeout();
    fn3();
  }, 0);
}
Copy after login

But doing so is equivalent to removing the original fn2Timeout and replacing it with one. New function, then insert the original fn2Timeout and fn3. This method of dynamically changing the original function has a special term called Monkey Patch. According to the mantra of our programmers: "It can definitely be done", but it is a bit awkward to write, and it is easy to get yourself involved. Is there a better way?
We take a step back and do not insist on waiting for fn2Timeout to be completely executed before executing fn3. Instead, we call it on the last line of the fn2Timeout function body:

function fn2() {
  setTimeout(function fn2Timeout() {
    console.log('第二个调用');
    fn3();    // 注{1}
  }, 0);
}
Copy after login

This looks better, but when defining fn2 There is no fn3 yet, where did this fn3 come from?

There is another problem. Since fn3 needs to be called in fn2, we cannot call fn3 through stack.forEach, otherwise fn3 will be called twice.

We cannot hardcode fn3 into fn2. On the contrary, we only need to find the next function of fn2 in the stack at the end of fn2Timeout, and then call:

function fn2() {
  setTimeout(function fn2Timeout() {
    console.log('第二个调用');
    next();
  }, 0);
}
Copy after login

This next function is responsible for finding the next function in the stack and executing it. Let’s implement next now:

var index = 0;

function next() {
  var fn = stack[index];
  index = index + 1; // 其实也可以用shift 把fn 拿出来
  if (typeof fn === 'function') fn();
}
Copy after login

next uses stack[index] to get the function in the stack. Every time next is called, the index will be incremented by 1, so as to achieve the purpose of fetching the next function.
Next is used like this:

var stack = [];

// 定义index 和next

function fn1() {
  console.log('第一个调用');
  next(); // stack 中每一个函数都必须调用`next`
};
stack.push(fn1);

function fn2() {
  setTimeout(function fn2Timeout() {
     console.log('第二个调用');
     next(); // 调用`next`
  }, 0);
}
stack.push(fn2, function() {
  console.log('第三个调用');
  next(); // 最后一个可以不调用,调用也没用。
});

next(); // 调用next,最终按顺序输出'第一个调用'、'第二个调用'、'第三个调用'。
Copy after login

Now that the stack.forEach line has been deleted, we call next by ourselves. Next will find the first function fn1 in the stack to execute, and call next in fn1. Go Find the next function fn2 and execute it, then call next in fn2, and so on.
Every function must call next. If it is not written in a certain function, the program will end directly after executing the function without any mechanism to continue.

After understanding this implementation of function queue, you should be able to solve the following interview question:

// 实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)
/* 输出: 
Hi! This is Hank!
*/

LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
/* 输出: 
Hi! This is Hank!
// 等待10秒..
Wake up after 10
Eat dinner~
*/

LazyMan(“Hank”).eat(“dinner”).eat(“supper”)
/* 输出: 
Hi This is Hank!
Eat dinner~
Eat supper~
*/

LazyMan(“Hank”).sleepFirst(5).eat(“supper”)
/* 等待5秒,输出
Wake up after 5
Hi This is Hank!
Eat supper
*/

// 以此类推。
Copy after login

Node.js The famous connect framework This is how middlewarequeue is implemented. If you are interested, you can take a look at its source code or this interpretation of "What is connect middleware".

If you are careful, you may see that this next can only be placed at the end of the function for the time being. If it is placed in the middle, the original problem will still occur:

function fn() {
  console.log(1);
  next();
  console.log(2); // next()如果调用了异步函数,console.log(2)就会先执行
}
Copy after login

redux and koa pass Different implementations can put next in the middle of the function, and then turn back and execute the code below next after executing the subsequent functions. This is very clever. Write again when you have time.

The above is the detailed content of Detailed explanation of JS queue functions and asynchronous execution examples. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 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

Go language indentation specifications and examples Go language indentation specifications and examples Mar 22, 2024 pm 09:33 PM

Indentation specifications and examples of Go language Go language is a programming language developed by Google. It is known for its concise and clear syntax, in which indentation specifications play a crucial role in the readability and beauty of the code. effect. This article will introduce the indentation specifications of the Go language and explain in detail through specific code examples. Indentation specifications In the Go language, tabs are used for indentation instead of spaces. Each level of indentation is one tab, usually set to a width of 4 spaces. Such specifications unify the coding style and enable teams to work together to compile

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

Oracle DECODE function detailed explanation and usage examples Oracle DECODE function detailed explanation and usage examples Mar 08, 2024 pm 03:51 PM

The DECODE function in Oracle is a conditional expression that is often used to return different results based on different conditions in query statements. This article will introduce the syntax, usage and sample code of the DECODE function in detail. 1. DECODE function syntax DECODE(expr,search1,result1[,search2,result2,...,default]) expr: the expression or field to be compared. search1,

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

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

See all articles