The root reason for using setTimeout to implement setInterval is: SetTimeout Pushes the current asynchronous task to the queue regardless of whether the last asynchronous task is completed (it is easy to understand that setTimeout itself is called once), and setInterval determines whether the last asynchronous task was executed when the task is pushed to the queue.
As a result, when setInterval performs periodic rotation training, time-consuming operations occur, or asynchronous operations are time-consuming, so that asynchronous tasks are not executed at the expected interval.
SetTimeout Ensures that the interval between calls is consistent. SetInterval includes the time to execute the callback.
Use setTimeout to implement setInterval
let timer = null;
function interval(func, delay){
let interFunc = function(){
func.call(null);
timer = setTimeout(interFunc, delay) // recursive call
}
timer = setTimeout(interFunc, delay) // Trigger recursion
}
/ / call
interval(() = > console.log("long"), 1000)
// Clear the timer
window.clearTimeout(timer)
Copy the code
Note: It is expected to stop the timer // TODO without introducing the global variable timer.
The delay parameter is used at two places in the interval function, which can be different, that is, the interval between the first execution and the subsequent code execution can be different.