


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();
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() });
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() }); // 按顺序输出'第一个调用'、'第二个调用'、'第三个调用'
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);
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() }); // 输出'第一个调用'、'第三个调用'、'第二个调用'
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); }
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); }
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); }
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(); }
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,最终按顺序输出'第一个调用'、'第二个调用'、'第三个调用'。
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 */ // 以此类推。
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)就会先执行 }
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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),