Why was setTimeout

OK, look at an example of what the output of this example is?

setTimeout(function(){
    console.log(1);
}, 0);
console.log(2);
console.log(3);
结果是 2,3,1
复制代码

This does not seem to follow the routine the cards, ah, obviously waiting for 0 milliseconds is not waiting for direct output, ah, but why 1 in the final output of it?

This need to figure out a very important concept: JS is single-threaded, single-threaded means, all tasks need to line up, before the end of a mission, a mission will be performed later. If a task takes a long time ago, a task after it had been waiting for. In fact well understood, as we go to the supermarket to buy things, like, all those who need to buy things checkout line at the cash register, the cashier at the same time each checkout is only one customer under normal circumstances, the customer can complete checkout services for the next customer.

  • In fact, when the js code execution encountered setTimeout (fn, millisec), fn will function on the task queue, when the js engine idle threads and reach millisec specified time before the fn js engine into the thread in execution.

setTimeout (fn, 0) meaning that the main thread to specify a task in the first available idle time to perform, that is, have to implement as early as possible. It added at the end of "task queue" of an event, and therefore have to wait until the task synchronization and the existing event "task queue" are processed, will be implemented. HTML5 standard specifies minimum setTimeout () of the second parameter (shortest space), not less than 4 msec, if less than this value, it will automatically increase. Prior to this, the old version of the browser will be the shortest interval to 10 milliseconds. In addition, for those DOM changes (particularly to the page re-rendering of the part), usually it does not happen immediately, but once every 16 milliseconds.

Note that, setTimeout () except that the event into a "task queue", must wait until the current code (execution stack) executed, the main thread will go to perform its specified callback function. If the current code takes a long time, it may have to wait a long time, and there is no way to guarantee the callback function will be () execution time specified in the setTimeout.

Guess you like

Origin blog.csdn.net/weixin_34411563/article/details/91384906