This problem is also in Baidu's front-end technical college encountered in the task needs to use JS to achieve the evaluation of the animation tutor SetInterval will lead to the bug did not understand the following to share their own learning process
Understand the single thread again
always say that JS is a single-threaded, in fact, I do not have a good understanding of the meaning of this single-threaded, such as my understanding of this settimeout (function () {},time) is to execute from now to time point of a piece of code, In fact, this understanding is problematic, the timer is just plan code in the future to execute, but this time is not guaranteed , this sentence can better help us understand JS single-threaded ( is it possible to understand that each code to JS single-threaded contention occupy )
In fact, JS can be imagined to run on a timeline, we add the event handler and Ajax callback is to add a certain code on this timeline, waiting for execution, the current period of code execution, the time line is idle, will execute the subsequent code, there is a scene is
var btn = document.getElementById ("btn"); Btn.addeventlistener ("click",function() { setTimeout()} (function() { Console.log (1); }; /* additional logic for event handlers */ }, false);
This example can fully reflect my previous misunderstanding, the above example when the corresponding click event, after 1000ms, a piece of code added to the JS execution of the timeline ( queue ), According to my previous understanding is 1000ms Console.log (1) will be executed, but the above example of the event handler in the execution time of the other logic is more than 1000ms,settimeout will not be done after 1000ms, because the need to wait The time line ( queue ) is idle, we understand the above example very well settimeout
SetInterval
Through the understanding of settimeout, found before the understanding of SetInterval also have problems, setinteral (function () {},time) My understanding is the interval of time to execute the code, but the code will interfere with each other, The switch between them, these problems I have not considered, setinterval will cause the bug I also confused
First of all, the function of setinterval is indeed to insert code in the timeline (queue) Every interval of time, and the JS engine provides such a mechanism, that is, when the code instance already exists in this timeline (queue), this code will not continue to add to the timeline (queue), This ensures that the minimum event interval that the timer's code is added to the queue is the specified interval, but there is a certain problem with this approach, which is the bug
(1) Some intervals will be skipped
(2) The number of timers may be smaller than expected before the code is executed
Understanding Timer Code Examples
Timer-related SetTimeout setinterval