requestAnimationFrame 实现 setInterval
function setInterval(callback, delay) {
let start = new Date().getTime();
let handle = {};
function loop() {
handle.value = requestAnimationFrame(loop);
let current = new Date().getTime();
let delta = current - start;
if (delta >= delay) {
callback.call();
start = new Date().getTime();
}
}
handle.value = requestAnimationFrame(loop);
return handle;
}
function customizeSetInterval(callback, interval) {
let timer = null;
let startTime = Date.now();
let loop = () => {
let endTime = Date.now();
if (endTime - startTime >= interval) {
startTime = endTime = Date.now();
callback(timer);
}
timer = window.requestAnimationFrame(loop);
}
loop();
return timer;
}
customizeSetInterval((timer) => {
console.log(1);
// cancelAnimationFrame(timer);
}, 1000)