When it comes to setinterval, you have to mention settimeout, both of which are used to perform a function on a regular basis, the difference being that settimeout is executed only once, and setinterval can be executed continuously, typically as follows:
function Do_sth () {console.log (' Hello ... ');}
settimeout (Do_sth, 2500); After 2.5 seconds, perform the Do_sth function (only once)
setinterval (do_sth, 3500);//3.5 seconds, execute the DO_STH function (execute once every 3.5 seconds, keep going)
On the surface, the two have their own uses, no problem. However, if the function performed by SetInterval is a time-consuming action, the setinterval will still call that function as planned, regardless of any previous blocking, so that the number of functions waiting to be executed in the queue will increase over time. The solution for this problem is still to use recursive calls to settimeout, such as:
function Do_sth () {
console.log (' Hello ... '); Even if the execution of the more time-consuming action is no problem,//
Wait here after the execution will be again to call settimeout
settimeout (do_sth, 2500);//Schedule follow-up implementation
}
do_sth (); //Initial implementation
This recursive invocation can not only achieve the purpose of looping through a function, but also prevent subsequent tasks from accumulating.
If you think this is a bit verbose, you can write a few more refinements:
(function () {
console.log (' Hello ... '); Do something here
settimeout (Arguments.callee, 2500);
}) ();
To say so, but if the scheduled task cost is very small, setinterval is generally not a problem, but if the task is expensive, make sure to use settimeout.