search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript queue functions and asynchronous execution

I have seen a similar queue function when referring to other people's JavaScript code, but I don't quite understand it. It turns out that this is to ensure that the functions are called in order. This article mainly introduces JavaScript queue functions and asynchronous execution methods to you. I hope it can help you.

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 = [];// 执行其他操作,定义fn1stack.push(fn1);// 执行其他操作,定义fn2、fn3stack.push(fn2, fn3);// 调用的时候stack.forEach(function(fn) { fn() });

It doesn’t matter whether the function has a name or not. You can just pass the anonymous function in 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通过stack[index]去获取stack中的函数,每调用next一次index会加1,从而达到取出下一个函数的目的。

next is used like this:

var stack = [];

// 定义index 和nextfunction 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,最终按顺序输出'第一个调用'、'第二个调用'、'第三个调用'。
现在stack.forEach一行已经删掉了,我们自行调用一次next,next会找出stack中的第一个函数fn1执行,fn1 里调用next,去找出下一个函数fn2并执行,fn2里再调用next,依此类推。

Every function must call next. If it is not written in a function, the program will directly execute the function after executing it. End, no mechanism to continue.

After understanding the 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 中大名鼎鼎的connect框架正是这样实现中间件队列的。有兴趣可以去看看它的源码或者这篇解读《何为 connect 中间件》。

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 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, through different implementations, can place next in the middle of the function, execute the subsequent functions and then turn back to execute the code below next. Very clever. Write again when you have time.

Related recommendations:

Share an encapsulated javascript event queue function code to solve the problem of binding events

Your own encapsulated javascript event Queue function version_javascript skills

jquery queue function usage example_jquery

The above is the detailed content of Detailed explanation of JavaScript queue functions and asynchronous execution. 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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

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

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),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.