The execution logic and difference between setTimeout() and setInterval():

Logical understanding: When the program executes setTimeout() and setInterval(), it will let these two run in the background (my understanding, whether this is the case or not, remains to be verified). When the time is up, the callback functions will be placed in the order. The tail of the currently executing function queue. Even if the delay is 0, the Javascript parser currently performing parsing will not immediately execute the timer's callback function (timers are equivalent to asynchronous, but there is a difference), but will still queue their callback functions in the current parsing queue The tail (or can be understood as the head of the next round of function queue).
 
Understanding the difference: the delay time for the callback function in setTImeout() to start executing is >= delay. To sum up, because sometimes other functions are executed during the delay process, if the execution time of those functions is greater than the delay time, it will be Causes "deferred execution" of the callback function in setTImeout().
The interval between the execution of the callback function in setInterval() <= delay: we all know that setInterval() will call its own callback function at a fixed time interval, and will not care whether the last callback function is executed or not, which is It means that if there are functions waiting to be executed before the last callback function, their overall execution time > delay time and there are no other functions waiting to be executed between the current callback function and the last callback function, it will cause a Case: The callback function in setTImeout() will be executed twice in a row.
Such as:
setTimeout(function() { // The interval time between each execution of this callback function >= 100
/*
a bunch of function bodies
*/
setTimeout(arguments.callee, 100)
}, 100)
 
setInterval(function () { // The interval time between each execution of this callback function <= 100
/*
a bunch of function bodies
*/
}, 100)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653511&siteId=291194637