setTimeout time is set to 0 detailed analysis
setTimeout() is a method belonging to window, but we all omit the top-level container name of window. This is used to set a time. When the time is up, a specified method will be executed. The following article mainly explains We have introduced relevant information about setting the setTimeout time to 0. Friends in need can refer to it.
Preface
This article mainly introduces to you the relevant content about setting the setTimeout time to 0, and shares it for your reference and study. The following words Not much more to say, let’s take a look at the detailed introduction.
1. Appetizer, what is setTimeout
First look at the explanation of setTimeout on w3school
The setTimeout(fn,millisec) method is used to call a function or calculated expression after a specified number of milliseconds.
It’s very simple, setTimeout()
Only execute fn once. When it is executed depends on the number of milliseconds set by the second parameter millisec, so many people are accustomed to calling it delay. It is nothing more than delaying for a period of time before executing the code inside.
setTimeout(function(){ console.log('我是setTimeout'); }, 1000);
Under normal circumstances, I am setTimeout. This sentence will not be output immediately but will be output in the browser console after 1000 milliseconds.
2. Main dish, js is single-threaded
OK, let’s look at an example. What is the output of this example? ?
setTimeout(function(){ console.log(1); }, 0); console.log(2); console.log(3);
To some people’s surprise, the results were 2, 3, 1. This does not seem to follow the routine. It obviously waits for 0 milliseconds, that is, it outputs directly without waiting. Why is 1 output at the end?
This requires clarification of a very important concept: js is single-threaded. Single-threading means that all tasks need to be queued, and the next task will not be executed until the previous task is completed. If the previous task takes a long time, the next task will have to wait.
In fact, it’s easy to understand. Just like everyone goes to the supermarket to buy things, all people buying things need to line up at the checkout counter to check out. Under normal circumstances, each checkout counter can only serve one person at a time. The customer checks out. Only after this customer checks out can the next customer be served.
The kernel of the browser is multi-threaded. They cooperate with each other under the control of the kernel to maintain synchronization. A browser implements at least three resident threads: JavaScript engine thread, GUI rendering thread, and browser events. Trigger thread.
The JavaScript engine is based on event-driven single-thread execution. The JS engine has been waiting for the arrival of tasks in the task queue and then processed them. The browser has only one JS thread at any time. Run JS program.
The GUI rendering thread is responsible for rendering the browser interface. This thread will be executed when the interface needs to be repainted (Repaint) or when a reflow (reflow) is caused by some operation. However, it should be noted that the GUI rendering thread and the JS engine are mutually exclusive. When the JS engine is executed, the GUI thread will be suspended, and GUI updates will be saved in a queue and executed immediately when the JS engine is idle.
Event trigger thread. When an event is triggered, the thread will add the event to the end of the pending queue and wait for processing by the JS engine. These events can come from the code block currently executed by the JavaScript engine such as setTimeOut, or from other threads in the browser kernel such as mouse clicks, AJAX asynchronous requests, etc. However, due to the single-threaded relationship of JS, all these events have to be queued for processing by the JS engine. (Asynchronous code will be executed when no synchronous code is executed in the thread)
In fact, when js code execution encounters setTimeout(fn,millisec)
, the fn function will be placed in the task queue. When the js engine thread is idle and reaches the time specified by millisec, fn will be placed in the js engine thread for execution.
setTimeout(fn,0)
means to specify a task to be executed in the earliest available idle time of the main thread, that is, to be executed as early as possible. It adds an event at the end of the "task queue", so it will not be executed until the synchronization task and the existing events in the "task queue" have been processed.
HTML5 standard stipulates that the minimum value (shortest interval) of the second parameter of setTimeout()
shall not be less than 4 milliseconds. If it is lower than this value, it will automatically increase. Prior to this, older browsers set the minimum interval to 10 milliseconds. In addition, those DOM changes (especially those involving page re-rendering) are usually not executed immediately, but every 16 milliseconds. At this time, the effect of using requestAnimationFrame()
is better than setTimeout()
.
It should be noted that setTimeout()
only inserts the event into the "task queue". The main thread must wait until the current code (execution stack) is finished executing before the main thread executes the specified task. Callback. If the current code takes a long time, you may have to wait for a long time, so there is no way to guarantee that the callback function will be executed at the time specified by setTimeout()
.
3. Dessert, the wonderful use of setTimeout
其实setTimeout是有一些妙用的,这里简单列举几个。
函数去抖
让一个函数在一定间隔内没有被调用时,才开始执行被调用方法。比如当你在使用 google 搜索内容的时候,有些关键词输入到一半,谷歌会展示一个可选列表,根据你当前输入的内容作出的一个猜测联想。需要监听文字改变,每一次改变都会调用一次回调函数,现在需要的一种实现是在用户停止键盘事件一段时间后,去发送一个请求。
var debounce = function(method, context) { clearTimeout(method.tId); method.tId = setTimeout(function(){ method.call(context); },100); }
轮训任务
js中可以使用setInterval开启轮询,但是这种存在一个问题就是执行间隔往往就不是你希望的间隔时间。
比如有个轮询任务间隔是100ms,但是执行方法的时间需要450ms,那么在200ms、300ms、400ms本来是计划中执行任务的时间,浏览器发现第一个还未执行完,那么就会放弃2、3、4次的任务执行,并且在500ms之后再次执行任务,这样的话,其实再次执行的间隔就只有50ms。使用setTimeout构造轮询能保证每次轮询的间隔。
setTimeout(function () { console.log('我被调用了'); setTimeout(arguments.callee, 100); }, 100);
延迟js引擎的调用
var p = document.createElement('p'); p.innerHTML = '我是一个p'; p.setAttribute('style', 'width:200px; height:200px;background-color:#f00; '); document.body.appendChild(p); setTimeout(function() { console.log('我被调用了'); }, 1000);
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of setTimeout time is set to 0 detailed analysis. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In-depth analysis of the role and application scenarios of HTTP status code 460 HTTP status code is a very important part of web development and is used to indicate the communication status between the client and the server. Among them, HTTP status code 460 is a relatively special status code. This article will deeply analyze its role and application scenarios. Definition of HTTP status code 460 The specific definition of HTTP status code 460 is "ClientClosedRequest", which means that the client closes the request. This status code is mainly used to indicate

iBatis and MyBatis: Differences and Advantages Analysis Introduction: In Java development, persistence is a common requirement, and iBatis and MyBatis are two widely used persistence frameworks. While they have many similarities, there are also some key differences and advantages. This article will provide readers with a more comprehensive understanding through a detailed analysis of the features, usage, and sample code of these two frameworks. 1. iBatis features: iBatis is an older persistence framework that uses SQL mapping files.

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

Due to space limitations, the following is a brief article: Apache2 is a commonly used web server software, and PHP is a widely used server-side scripting language. In the process of building a website, sometimes you encounter the problem that Apache2 cannot correctly parse the PHP file, causing the PHP code to fail to execute. This problem is usually caused by Apache2 not configuring the PHP module correctly, or the PHP module being incompatible with the version of Apache2. There are generally two ways to solve this problem, one is

Detailed analysis and examples of exponential functions in C language Introduction: The exponential function is a common mathematical function, and there are corresponding exponential function library functions that can be used in C language. This article will analyze in detail the use of exponential functions in C language, including function prototypes, parameters, return values, etc.; and give specific code examples so that readers can better understand and use exponential functions. Text: The exponential function library function math.h in C language contains many functions related to exponentials, the most commonly used of which is the exp function. The prototype of exp function is as follows
