Home >Web Front-end >JS Tutorial >setTimeout instance
function test1(){ console.log('t1'); }function test2(){ setTimeout(test1,0); console.log('t2'); }
The output results are t2, t1.
Strange, setTimeout has not been set to 0 and should be executed first, but the result is not like this.
To understand this problem, we need to review the function call stack of javaScript.
JS calls functions using the stack to maintain the function. When a function is called, the function is pushed onto the stack. After the function finishes running, the function is popped off the stack.
The bad thing here is that if a certain function is executed for too long, subsequent operations will have to wait, thus causing blocking
The best way is Use asynchronous to perform some time-consuming operations, and the code behind the js script can be executed.
When js script code is executed, the function to be executed is put into the call stack, which is the Call Stack in the picture. If you encounter some browsers Events are added to Web Apis, and both the call stack and browser events can put some time-consuming functions into the circular queue.
For example: setTimeout(fn,timeer) $.ajax, etc., so that the main thread can perform other operations. When there is no function call in the call stack, the main thread will call the function in the message queue from the message in the circular queue. .
Finally, the time in setTimeout(fn, time) is only the fastest time that the fn function can be executed. The actual execution time may be equal to or greater than the defined time
The above is the detailed content of setTimeout instance. For more information, please follow other related articles on the PHP Chinese website!