Home  >  Article  >  Web Front-end  >  setTimeout instance

setTimeout instance

一个新手
一个新手Original
2017-09-26 09:40:361506browse


setTimeout

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.

javaScript function call stack

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.
setTimeout instance
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.

Function calling mechanism

setTimeout instance
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!

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