Home >Web Front-end >JS Tutorial >A brief discussion on setTimeout and setInterval_javascript techniques
When I was writing the latest code, I saw someone using setTimeout(fun,0) in the project, so I wanted to summarize it. Personal understanding, please point out if there are any mistakes. THX
To understand how JavaScript timers work, you must first understand that the JavaScript engine is single-threaded. This can be understood as the JavaScript engine is a waiter. It has a service queue. All interface element events, scheduled trigger callbacks, and asynchronous request callbacks are queued in this task queue, waiting for processing. All tasks are a minimal unit and do not interrupt processing. In this way, you can understand setTimeout(fun,0). It does not mean that the code will be executed immediately unless the task queue is empty (in fact, there are differences in how each browser actually executes this. Newer browsers actually It may be at 4ms; the older version may be longer, 16ms is also possible). And setTimeout(fun, time) means how long it will take to add the fun callback to this task queue, that is, it will take at least time to execute fun.
For example:
setTimeout(function () { console.log(1); }, 0); var tem = 0; for (var i = 1; i < 1000000; i++) { tem += i; }; console.log(2);
Display the result as
That is to say, when executing setTimeout, 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, and only goes to the task list after this code segment is executed. Get a new task, so the result is to display 2 first and then 1.
The setInterval(fun, time) method is to add fun to the queue at certain intervals. So the question is, what if the execution time of fun is longer than time?
Look at 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 100ms and clear the timer after 1s. But what about the result?
The result is displayed as
In other words, in fact, it has not been executed that many times. That is to say, some intervals will be skipped, so the interval between multiple code executions may be smaller than expected. It turns out that when the timer code is added to the queue, if the timer code instance exists, the timer code will be skipped.
Quoting a picture will make it easy to understand.
The above is the entire content of this article, I hope you all like it.