Skip to content

使用 requestAnimationFrame 模拟 setInterval

Published: at 07:43 PMSuggest Changes

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)

备注


Previous Post
JS 生成测试数据
Next Post
JS 更改树状数据的几种方式