In fact, setTimeout and setInterval have the same syntax. They all have two parameters: one is the code string to be executed, and the other is the interval in milliseconds. after that period, the code will be executed. However, when there are differences between the two functions in the latest code writing, we can see that someone in the project uses setTimeout (fun, 0), so I would like to summarize it. I personally understand that if there are any errors, please point them out. THX
To understand how the JavaScript timer works, you must first understand that the JavaScript engine is single-threaded. It can be understood that the javascript engine is a waiter who has a queue of services, all interface element events, timed trigger callbacks, and asynchronous request callbacks must all be queued in this task queue, wait for processing. All tasks are a minimum unit and will not be interrupted. In this way, you can understand setTimeout (fun, 0). it does not mean that the code is executed immediately, unless the task queue is empty (in fact, there are also differences between browsers in actual execution. compared with new browsers, the actual version may be 4 ms; the old version may be a little longer, and 16 ms is also possible ). SetTimeout (fun, time) indicates how much time the fun callback will be added to the task queue, that is, at least time is required for fun execution.
For example:
setTimeout(function () { console.log(1);}, 0);var tem = 0;for (var i = 1; i < 1000000; i++) { tem += i;};console.log(2);
The result is
The code is as follows:
2
1
That is to say, when setTimeout is executed, the function callback is added to the task queue, but it is not executed immediately, because the js engine is still busy processing the current js, the new task is retrieved from the task list only after the code segment is executed. Therefore, the result is displayed 2 and 1.
The setInterval (fun, time) method is to add fun to the queue at regular intervals. The question is, what if the execution time of fun is longer than the time?
Read a piece of code
var num = 0;var time = setInterval(function () { var tem = 0; for (var i = 1; i < 99999999; i++) { tem += i; }; num ++; console.log(num);}, 100);setTimeout(function (){ clearInterval(time);}, 1000);
It means to execute a piece of code every MS and clear the timer after 1 s. But what about the results?
The result is
The code is as follows:
1
2
3
That is to say, in fact, it has not been executed for so many times. That is to say, some intervals will be skipped, which means the interval between multiple code executions may be smaller than expected. When the timer code is added to the queue, if the code instance of the timer exists, the timer code will be skipped.
Referencing an image is easy to understand.
The above is all the content of this article. I hope you will like it.