


Take you step by step to understand asynchronous programming in JavaScript
This article will introduce you to asynchronous programming in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Asynchronous means non-synchronous....
This section may be a bit boring, but it is a very important concept in JavaScript and is very useful. It is necessary to learn.
Purpose
- Improve development efficiency and write easy-to-maintain code
Introduction question
- Why does the page get stuck when requesting? ?
$.ajax({ url: "www.xx.com/api", async: false, // true success: function(result) { console.log(result); }, });
- Why is the data updated but the DOM not updated? ?
// 异步批量更新DOM(vue-nextTick) // <p id="app">{{num}}</p> new Vue({ el: "#app", data: { num: 0, }, mounted() { let dom = document.getElementById("app"); while (this.num !== 100) { this.num++; } console.log("Vue num=" + this.num, "DOM num=" + dom.innerHTML); // Vue num=100,DOM num=0 // nextTick or setTimeout }, });
The reasons for asynchronous generation
Cause: single thread (one point in time, only do one thing), the browser's JS engine is single threaded caused.
Single thread means that there is only one thread responsible for interpreting and executing IavaScript code in the JS engine. You might as well call it the main thread.
The so-called single thread means that only one task can be completed at a time. If there are multiple tasks, they must be queued. The previous task is completed before the next task is executed.
First take a look at the thread diagram of the browser kernel:
Among them, The rendering thread and the JS thread are mutually exclusive .
Suppose there are two functions, one modifying and one deleting, operating a DOM node at the same time. If there are multiple threads, if the two threads are executed at the same time, there will definitely be a deadlock and there will be problems.
Why JS should be designed as single-threaded, because of the special environment of the browser.
Advantages and disadvantages of single thread:
The advantage of this mode is that it is relatively simple to implement and the execution environment is relatively simple; The disadvantage is that as long as one task takes a long time, the subsequent Tasks must be queued and waited, 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.
Common blockage (infinite loop):
while (true) {}
JS was originally designed to be a script language that runs in the browser, so we didn’t want to make it so complicated, so we just designed It has become a single thread, that is, can only do one thing at a time.
In order to solve single-thread blockingthis shortcoming: asynchronous is generated.
Take the example of eating instant noodles:
- Synchronous: Buy instant noodles => Boil water (staring) => Cook noodles => Eat instant noodles
- Asynchronous : Buy instant noodles => Boil water (the water boils and the kettle sounds - callback) => Watch TV => Cook noodles (the noodles are ready and the kettle rings - callback) => Watch TV => Call me when it's done => Eat instant noodles
Watching TV is an asynchronous operation, and the sound of the kettle is a callback function.
Asynchronous Programming
Most of the code in JS is executed synchronously. Only a few functions are executed asynchronously. Asynchronously executed code requires asynchronous programming. .
Asynchronous code
setTimeout(() => { console.log("log2"); }, 0); console.log("log1"); // ?? log1 log2
Characteristics of asynchronous code: It is not executed immediately, but needs to wait and be executed at a certain point in the future.
Synchronous code | Asynchronous code |
---|---|
##![]() Hot AI Tools![]() Undresser.AI UndressAI-powered app for creating realistic nude photos ![]() AI Clothes RemoverOnline AI tool for removing clothes from photos. ![]() Undress AI ToolUndress images for free ![]() Clothoff.ioAI clothes remover ![]() Video Face SwapSwap faces in any video effortlessly with our completely free AI face swap tool! ![]() Hot ArticleAssassin's Creed Shadows: Seashell Riddle Solution 4 weeks agoByDDD What's New in Windows 11 KB5054979 & How to Fix Update Issues 3 weeks agoByDDD Where to find the Crane Control Keycard in Atomfall 4 weeks agoByDDD Roblox: Dead Rails - How To Complete Every Challenge 1 months agoByDDD How to fix KB5055523 fails to install in Windows 11? 2 weeks agoByDDD ![]() Hot Tools![]() DVWADamn 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 ![]() mPDFmPDF 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), ![]() Dreamweaver CS6Visual web development tools ![]() SublimeText3 Linux new versionSublimeText3 Linux latest version ![]() SublimeText3 Chinese versionChinese version, very easy to use ![]() Hot Topics |