About the use of setInterval and setTimeout in JavaScript, settimeinterval
When it comes to setInterval, we have to mention setTimeout, both of which are used to regularly execute a function. The difference is that setTimeout is only executed once, And setInterval can be continuously executed. The typical usage is as follows:
function do_sth() { console.log('Hello...'); }
SetTimeout (do_something, 2500); // After 2.5 seconds, execute the do_something function (only once) setInterval (do_something, 3500); // After 3.5 seconds, execute the do_something function (execute every 3.5 seconds and keep running)
On the surface, the two have their own purposes and there is no problem. However, if the setInterval function is a time-consuming action, setInterval still calls the function according to the original plan without considering any previous blocking. As a result, over time, more and more functions are waiting for execution in the queue. The solution to this problem is still to call setTimeout recursively, for example:
Function do_something () {console. log ('Hello... '); // It is okay even if the time-consuming action is executed here. // the setTimeout (do_something, 2500) will be called after the execution is completed ); // schedule subsequent execution} do_something (); // initial execution
This method of recursive calling can achieve the purpose of executing a function cyclically and prevent subsequent tasks from accumulating.
If you think this method is a bit wordy, you can write it more refined:
(function() { console.log('Hello...'); // do something here setTimeout(arguments.callee, 2500);})();
In this case, if the scheduled execution task overhead is very small, setInterval is normal. However, if the task overhead is large, use setTimeout.