SetTimeout time is set to 0 for detailed parsing, and settimeout for parsing
Preface
This article describes how to set the setTimeout time to 0 and share it with you for your reference. I will not talk about it later. Let's take a look at the detailed introduction.
1. appealer, What Is setTimeout?
First, let's take a look at the explanation of setTimeout in w3school.
The setTimeout (fn, millisec) method is used to call a function or computation expression after a specified number of milliseconds.
Very simple,setTimeout()
The execution of fn only once depends on the number of milliseconds set by millisec, the second parameter. Therefore, many people prefer to call it latency, which is nothing more than waiting for a period of time before executing the code.
SetTimeout (function () {console. log ('I am settimeout') ;}, 1000 );
Under normal circumstances, the setTimeout statement will not be output immediately, but will be output in the browser console after 1000 milliseconds.
2. Main course. js is single-threaded.
OK. Let's look at an example. What is the output result of this example?
setTimeout(function(){ console.log(1);}, 0);console.log(2);console.log(3);
To some people's expectation, the result is 2, 3, and 1. This does not seem to play the cards by the way. It is clearly waiting for 0 milliseconds, that is, not waiting for direct output. Why is 1 being output at the end?
This requires us to understand a very important concept: js is a single thread, and a single thread means that all tasks need to be queued and the previous task ends before executing the next task. If the previous task takes a long time, it will have to wait.
In fact, it is easy to understand that, just as everyone goes to the supermarket to buy things, all the people who buy things need to queue up at the cashier to settle the bills. Normally, each cashier can only settle the bills for one customer at a time, this customer can only serve the next customer after the checkout is completed.
The browser kernel is multi-threaded. They work with each other under the kernel control to maintain synchronization. A browser must implement at least three resident threads: javascript Engine threads and GUI rendering threads, browser event trigger thread.
- The javascript engine is based on the event-driven single-thread execution. The JS engine keeps waiting for the arrival of tasks in the task queue and then processes them, the browser has only one JS thread running the JS program at any time.
- The GUI rendering thread is responsible for rendering the browser interface. When the interface needs to be repainted or reflow is triggered due to some operation, this thread will execute. However, you must note that the GUI rendering thread and JS engine are mutually exclusive. When the JS engine is executed, the GUI thread will be suspended, GUI updates are saved in a queue and executed immediately when the JS engine is idle.
- Event trigger thread. When an event is triggered, the thread adds the event to the end of the queue to be processed, waiting for processing by the JS engine. These events can come from the code blocks currently executed by the JavaScript engine, such as setTimeOut, other threads from the browser kernel, such as mouse clicks and AJAX asynchronous requests, however, because of the single-threaded relationship of JS, all these events have to be queued for processing by the JS engine. (Asynchronous code is executed only when no synchronous code is executed in the thread)
In fact, when JavaScript code execution encounterssetTimeout(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, the fn will be put into the js engine thread for execution.
setTimeout(fn,0)
The meaning is to specify the earliest available idle time of a task in the main thread, that is, to execute as early as possible. It adds an event at the end of the "task queue". Therefore, it can be executed only after the existing events of the synchronization task and the "task queue" are processed.
The HTML5 Standard specifiessetTimeout()
The minimum value (the shortest interval) of the second parameter, which must not be less than 4 ms. If it is lower than this value, it will automatically increase. Earlier versions of browsers set the shortest interval to 10 ms. In addition, DOM changes (especially those involving page re-rendering) are usually not executed immediately, but every 16 milliseconds. UserequestAnimationFrame()
The effect is bettersetTimeout()
.
Note that,setTimeout()
Only after the event is inserted into the "task queue", the main thread will execute the specified callback function after the current Code (execution stack) is executed. If the current Code takes a long time, it may take a long time, so there is no way to ensure that the callback function will certainlysetTimeout()
Execution at the specified time.
3. Dessert and the wonderful use of setTimeout
In fact, setTimeout has some advantages. Here are a few simple examples.
Function shake
When a function is not called within a certain interval, the called method is executed. For example, when you use google to search for content, if some keywords are entered in half, google will display an optional list and make a guess based on your current input. You need to listen for text changes. Each change calls a callback function. Now, you need to send a request after the user stops the keyboard event for a period of time.
var debounce = function(method, context) { clearTimeout(method.tId); method.tId = setTimeout(function(){ method.call(context); },100);}
Rotation task
In js, you can use setInterval to enable polling. However, the execution interval is often not the expected interval.
For example, if there is a polling task with an interval of 100 ms but the execution method takes 450 ms, then 200 ms, 300 ms, and ms are originally the scheduled task execution time, if the browser finds that the first task has not been completed, it will discard the 2, 3, and 4 tasks and execute the task again after Ms. In this case, in fact, the interval for re-execution is only 50 ms. Using setTimeout to construct a polling can ensure the interval of each polling.
SetTimeout (function () {console. log ('I was called'); setTimeout (arguments. callee, 100) ;}, 100 );
Delay js engine calls
Var div = document. createElement ('div '); div. innerHTML = 'I am a div'; div. setAttribute ('style', 'width: 200px; height: 200px; background-color: # f00; '); document. body. appendChild (div); setTimeout (function () {console. log ('I was called');}, 1000 );
Although setTimeout has some advantages, it does add tasks in the macro task queue, so it cannot be abused.
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.