search
HomeWeb Front-endJS Tutorial(Common interview questions) js basics from setTimeout to asynchronous principle of js

These are some very basic but easily overlooked issues. Everyone knows how to use this method but has not studied in depth what the process is. Without further ado, look at the code below

 <input type="text" value="a" name="input" onkeydown="alert(this.value)" />
<input type="text" value="a" name="input" onkeydown="var me=this;setTimeout(function(){alert(me.value)},0)" >

When one keydown is performed, the original value in the input pops up, but when the second keydown is performed, the updated value pops up. This is because setTimeout, although its delay is set to 0, is triggered almost immediately. But it is still added to the back of the execution queue, but for this asynchronous process, the rendering has been completed. When the callback function is executed, the output is already the updated value. Another problem here is that this indicates different objects inside and outside different functions. When there is a function in the function, pay more attention to this. It is easy to make mistakes. Just be careful and don't say much.

Next, js js is single-threaded. It is conceivable that if there is no multi-threading, the entire program will be stuck. Fortunately, the browser is multi-threaded, and the browser makes js asynchronous. Some attributes of js: js is a single-threaded language. The browser only assigns one main thread to js to execute tasks (functions), but only one task can be executed at a time. These tasks form a task queue waiting to be executed, but certain tasks on the front end Some tasks are very time-consuming, such as network requests, timers and event monitoring. If they are queued up to wait for execution like other tasks, the execution efficiency will be very low and even cause the page to freeze. Therefore, the browser has opened up additional threads for these time-consuming tasks, mainly including http request threads, browser timing triggers, and browser event trigger threads. These tasks are asynchronous.

The browser opens a separate thread for asynchronous tasks such as network requests. So the question is, how does the main thread know after these asynchronous tasks are completed? The answer is the callback function. The entire program is event-driven. Each event will be bound to the corresponding callback function. For example, there is a piece of code that sets a timer.

setTimeout(function(){
    console.log(time is out);
},500);

When this code is executed, browse The server performs timing operations asynchronously. When 500ms arrives, a timing event will be triggered. At this time, the callback function will be placed in the task queue. The entire program is driven by such events.
So, js has always been single-threaded, and the browser is the key to achieving asynchronous

The following is transferred from the Internet:

js has been doing a job, which is to retrieve data from the task queue Extract the task and put it into the main thread for execution. Let’s have a deeper understanding below.
event loop
The picture comes from Philip Roberts' speech "Help, I'm stuck in an event-loop" is very profound!
Let’s map the concept we just learned to the picture. The threads that the browser opens for asynchronous tasks mentioned above can be collectively understood as WebAPIs. The task queue mentioned above is the callback queue. What we call The main thread is the part composed of dotted lines. The heap and stack together form the js main thread. The execution of functions is achieved by pushing and popping the stack. For example, there is a foo() function in the picture. The main thread pushes it into the stack. When executing the function body, it finds that the above functions still need to be executed, so it pushes these functions into the stack. When the function is executed, the function is popped off the stack. When the stack is cleared, it means that a task has been executed. At this time, the next task will be searched from the callback queue and pushed into the stack (this search process is called event loop, because it always loops to find whether there is a task in the task queue. There are also tasks).

Related articles:

Detailed explanation of js asynchronous file loader, detailed explanation of js asynchronous loading

How does native JS implement asynchronous requests to implement Ajax

Related videos:

JS#jQuery width and height understanding and application

The above is the detailed content of (Common interview questions) js basics from setTimeout to asynchronous principle of js. 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
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!