Home > Article > Web Front-end > Do you really understand the difference between setTimeout and setInterval?_javascript skills
You may even mistakenly interpret two functions that implement scheduled calls as something similar to threads, thinking that the called functions will be executed concurrently within a time slice. This seems very good and powerful, but in fact it is not the case. In fact, The situation is that javascript runs in the browser's javascript engine in a single-threaded manner. The function of setTimeout and setInterval is just to insert the code you want to execute into a code queue maintained by the js engine at a time point you set. , inserting the code queue does not mean that your code will be executed immediately, it is important to understand this. And setTimeout and setInterval are a little different.
Let’s talk about setTimeout first
Same as above, we assume that through a click, setInterval is triggered to execute the process code every other time period
For example, onclick needs to be executed in 300ms, block1 code is executed, setInterval is executed at 5ms, and this is a time point. The process code is inserted at 205ms, the click code ends successfully, and the process code starts executing (equivalent to the figure) timer code), however, the process code also executed for a relatively long time, exceeding the next insertion time point of 405ms. In this way, another process code was inserted after the code queue, and the process continued to execute, and the insertion time of 605ms was exceeded. Click, here comes the question. You may also think that another process code will be inserted after the code queue... The real situation is that since there is already an unexecuted process code in the code queue, the insertion time is 605ms. The point will be "mercilessly" skipped, because the js engine only allows one unexecuted process code. I wonder if you will suddenly become enlightened after talking about this...
For this case you can use a better form of code
I think if you think about this for a while, you will understand the benefits of it, so that there will be no problems with time points being skipped. That’s it. I hope it can be helpful. Maybe I didn’t express it very clearly. If you feel that your English is The basics are good and you can watch it directly
contains the section about advanced Timers. Personally, I think this book is really good. Whether you want to start from scratch, or you just need to look through it for reference. The author is from yahoo. A very good front-end development engineer: )