search
HomeWeb Front-endJS TutorialIntroduction to the principles and implementation techniques of asynchronous javascript_javascript techniques

Due to work needs, I need to write a script on the web page to submit data to the system in batches through the web page. So I thought of the Greasemonkey plug-in, so I started writing it and found that the problem was solved smoothly. But when summarizing and organizing the script, I habitually asked myself a question: Can it be simpler?
My answer is of course “yes”.

First review my requirements for batch submission of data: I have a batch of user data to be inserted into the system, but because the system library table structure is not determinant, it cannot be converted into SQL statements for insertion. There are nearly 200 pieces of data to be inserted. Even if it is entered into the system manually, it will probably take a day. As a programmer, of course I would not do such a stupid thing, I must use a program to solve it. This programming process took me 1 day. Compared with manual entry, my extra income is from this blog post, which is absolutely cost-effective!

It didn’t take any time to choose the programming platform. I directly chose to write my own script based on Greasemonkey. The browser was of course Firefox. The working process of the script:
Pre-store the data to be inserted in the script
Simulate a mouse click to open the input window on the page
Enter the data into the input window, and simulate clicking the "Submit" button to submit the data submitted to the system.
Loop in sequence until all data is processed.

The technical difficulty here is:
To open the input window, you need to wait for an irregular period of time, depending on the network conditions.
Submit data to the background, and you need to wait for the processing to be completed before you can cycle to the next data.
If I were a novice, of course I would directly write an application logic similar to this:

Copy code The code is as follows:

for(var i = 0; i { 3: clickButtonForInputWindow();
waitInputWindow();
enterInputData(dataArray[i] );
clickSubmitButton();
waitInputWindowClose();
}

In fact, all browsers will fall into a white screen after a few minutes and prompt "No response" and was forcibly terminated. The reason is that when the browser calls JavaScript, the main interface stops responding because the CPU is handed over to js for execution and there is no time to process interface messages.

In order to meet the requirement of "no locking", we can modify the script as follows:
Copy code The code is as follows:

for(var i = 0; i {
setTimeout(clickButtonForInputWindow);

setTimeout(waitInputWindowClose );
}

In fact, setTimeout and setInterval are the only asynchronous operations that browsers can support. How to use these two functions more elegantly to implement asynchronous operations? The current simple answer is Lao Zhao's Wind.js. Although I have not used this function library, the $await call alone meets my consistent requirement for simplicity. But for a single file script like mine, downloading an external js library from the Internet is obviously not as fast and enjoyable as copying a piece of code that supports asynchronous operations.

So I decided to find another way and make an asynchronous function library that does not require compilation and is easier to use and can be copied and pasted.

Before talking about asynchronous, let’s recall the several structural types of synchronous operations:

Sequence: It is the order in which statements are executed
Judgment: It is the judgment statement
Loop: strict It should be jump (goto), but most modern languages ​​have canceled goto. A loop should actually be a composite structure, a combination of if and goto.
The difficulty of asynchronous operations lies in two places:

Asynchronous judgment: The judgment in asynchronous situations is basically to detect that the conditions are satisfied, and then perform certain actions.
Asynchronous sequence: After each step in the sequence, control is returned and the next step is waited for in the next time slice. The difficulty is maintaining order. Especially when there is an asynchronous loop between two sequential actions.
Asynchronous loop: After each loop, control is returned to the browser, and this loop continues until the end of the run.
The simplest implementation is of course an asynchronous loop. My implementation code is as follows:
Copy code The code is as follows:

function asyncWhile(fn, interval)
{
if( fn == null || (typeof(fn) != "string" && typeof(fn) != "function") )
return;
var wrapper = function()
{
if( (typeof(fn) == "function" ? fn() : eval(fn) ) !== false )
setTimeout(wrapper, interval == null? 1: interval);
}
wrapper();
}

The core content is: if the return value of the fn function is not false, continue with the next setTimeout registration call.

In fact, the "wait and execute" logic is basically an asynchronous loop problem. An example of how to implement this situation is as follows:
Copy code The code is as follows:

asyncWhile(function (){
if( xxxCondition == false )
return true; // Indicates that the loop continues
else
doSomeThing();
return false; // Indicates that there is no need to continue the loop
});

For non-waiting and execution logic, a simple setTimeout is enough.
Asynchronous is easy, but the difficulty is to implement the order in asynchronous. The earliest reason was that I wanted to implement 3 steps, but the second part was an asynchronous loop of more than 100 times. In other words, the 3-step operation I want to implement is actually 103 sequential asynchronous operations. In order to find a way to implement responsive waiting in the browser, I searched my brain and only found an implementation in Firefox, and I had to apply for privileged calls.
Finally, I came up with a simple method, which is to introduce the concept of "Execution Chain". All registration functions of the same execution chain are sequential, and there is no relationship between different execution chains. In addition, it does not provide concepts such as mutual exclusion (mutex). If you want to synchronize, check it yourself in the code.
In the same execution chain, an execution token is saved. Only when the token matches the function serial number can execution be allowed, thus ensuring the order of asynchronous execution.
Copy code The code is as follows:

function asyncSeq(funcArray, chainName, abortWhenError)
{
if( typeof(funcArray) == "function" )
return asyncSeq([funcArray], chainName, abortWhenError);

if( funcArray == null || funcArray.length == 0 )
return;

if( chainName == null ) chainName = "__default_seq_chain__";
var tInfos = asyncSeq.chainInfos = asyncSeq.chainInfos || {};
var tInfo = tInfos[chainName] = tInfos[chainName] || {count : 0, currentIndex : -1, abort : false};

for(var i = 0; i {
asyncWhile(function(item, tIndex){
return function(){
if( tInfo.abort )
return false;
if( tInfo.currentIndex return true;
else if( tInfo.currentIndex == tIndex )
{
try{
item();
}
catch(e){
if ( abortWhenError ) tInfo.abort = true;
}
finally{
tInfo.currentIndex ;
}
}
else
{
if( abortWhenError ) tInfo. abort = true;
}
return false;
};
}(funcArray[i], tInfo.count ));
}

setTimeout(function() {
if( tInfo.count > 0 && tInfo.currentIndex == -1 )
tInfo.currentIndex = 0;
},20); // For debugging reasons, a delayed start is added
}

Thus, an asynchronous js function library supporting Copy&Paste is completed. Specific usage examples are as follows:
Copy code The code is as follows:

function testAsync()
{
asyncSeq([function(){println("aSyncSeq -0 ");}
, function(){println("aSyncSeq -1 ");}
, function(){println("aSyncSeq -2 ");}
, function(){println("aSyncSeq -3 ");}
, function(){println("aSyncSeq -4 ");}
, function(){println("aSyncSeq -5 ");}
, function(){println("aSyncSeq -6 ");}
, function(){println("aSyncSeq -7 ");}
, function(){println("aSyncSeq -8 ");}
, function(){println("aSyncSeq -9 ");}
, function(){println("aSyncSeq -10 ");}
, function(){println("aSyncSeq -11 ");}
, function(){println("aSyncSeq -12 ");}
, function(){println("aSyncSeq -13 ");}
, function(){println("aSyncSeq -14 ");}
, function(){println("aSyncSeq -15 ");}
, function(){println("aSyncSeq -16 ");}
, function(){println("aSyncSeq -17 ");}
, function(){println("aSyncSeq -18 ");}
, function(){println("aSyncSeq -19 ");}
, function(){println("aSyncSeq -20 ");}
, function(){println("aSyncSeq -21 ");}
, function(){println("aSyncSeq -22 ");}
, function(){println("aSyncSeq -23 ");}
, function(){println("aSyncSeq -24 ");}
, function(){println("aSyncSeq -25 ");}
, function(){println("aSyncSeq -26 ");}
, function(){println("aSyncSeq -27 ");}
, function(){println("aSyncSeq -28 ");}
, function(){println("aSyncSeq -29 ");}
]);

asyncSeq([function(){println("aSyncSeq test-chain -a0 ");}
, function(){println("aSyncSeq test-chain -a1 ");}
, function(){println("aSyncSeq test-chain -a2 ");}
, function(){println("aSyncSeq test-chain -a3 ");}
, function(){println("aSyncSeq test-chain -a4 ");}
, function(){println("aSyncSeq test-chain -a5 ");}
, function(){println("aSyncSeq test-chain -a6 ");}
, function(){println("aSyncSeq test-chain -a7 ");}
, function(){println("aSyncSeq test-chain -a8 ");}
], "test-chain");

asyncSeq([function(){println("aSyncSeq -a0 ");}
, function(){println("aSyncSeq -a1 ");}
, function(){println("aSyncSeq -a2 ");}
, function(){println("aSyncSeq -a3 ");}
, function(){println("aSyncSeq -a4 ");}
, function(){println("aSyncSeq -a5 ");}
, function(){println("aSyncSeq -a6 ");}
, function(){println("aSyncSeq -a7 ");}
, function(){println("aSyncSeq -a8 ");}
]);
}

var textArea = null;

function println(text)
{
if( textArea == null )
{
textArea = document.getElementById("text");
textArea.value = "";
}

textArea.value = textArea.value text "rn";
}

最后,要向大家说一声抱歉,很多只想拿代码的朋友恐怕要失望了,如果你真的不知道怎么处理这些多余的行号,你可以学习一下正则表达式的替换,推荐用UltraEdit。
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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!