function a(){ setTimeout(function() {alert(1)}, 0); alert(2); } a();
Pay attention to this code The setTimeout delay is set to 0, which means the delay is 0 milliseconds. It seems to be executed immediately without any delay, that is, 1,2. But the actual execution result is indeed 2,1. Why? This starts with the functions of Javascript call stack and setTimeout.
First of all, JavaScript is single-threaded, that is, only one code is executed at the same time, so each JavaScript code execution block will "block" the execution of other asynchronous events. Secondly, like other programming languages, function calls in Javascript are also implemented through the stack. When executing function a, a is pushed onto the stack first. If setTimeout is not added to alert(1), then alert(1) will be pushed onto the stack second, and finally alert(2). But now after adding setTimeout to alert(1), alert(1) is added to a new stack to wait and executed "as quickly as possible". This as fast as possible means to execute it immediately after the stack of a is completed, so the actual execution result is alert(2) first, and then alert(1). Here setTimeout actually removes alert(1) from the current function call stack. Look at the following example:
The purpose of such a function is to remove all the characters in the current input every time a character is entered. The alert comes out, but the actual effect is the content before the alert comes out and the button is pressed. Here, we can use setTimeout(0) to achieve this.
This way when the onkeydown event is triggered , the alert is put into the next call stack, and execution begins once the stack triggered by the onkeydown event is closed. Of course, the browser also has an onkeyup event that can also meet our needs.
Such setTimeout usage is still often encountered in actual projects. For example, the browser will smartly wait until the end of a function stack before changing the DOM. If the page background is first set from white to red and then back to white in this function stack, the browser will think that the DOM has not changed and ignore this. Two sentences, so we can add the "set back to white" function to the next stack through setTimeout, then we can ensure that the background color has changed (although it may not be noticed very quickly).
In short, setTimeout increases the flexibility of Javascript function calling and provides great convenience for scheduling the function execution sequence.
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