前端面试手写代码——使用 setTimeout 实现 setInterval

  • setTimeout: 倒计时后一次调用
  • setInterval: 间隔时间之间重复调用
// 方法一:递归套娃,套娃结束的时候,只是clearInterval是通过返回的属性设置
const setTimeoutToInterval = (fn, timeout) => {
  const timer = { flag: true };
  const interval = () => {
    if (timer.flag) {
      fn();
      setTimeout(interval, timeout);
    }
  };
  setTimeout(interval, timeout);
  return timer;
};
const fn = () => console.log("------interval------");
const curTimer = setTimeoutToInterval(fn, 1000);
setTimeout(() => {
  curTimer["flag"] = false;
}, 6000);

//   方法二:递归——直接套娃,本质和方法一并无二致
const _setTimeoutToInterval = (fn, timeout, times) => {
  if (!times) return;
  setTimeout(() => {
    fn();
    _setTimeoutToInterval(fn, timeout, --times);
  }, timeout);
};

//   方法三:递归——具名回调函数 + clearTimeout
const __setTimeoutToInterval = (fn, timeout, times) => {
  let timer = setTimeout(function aa() {
    fn();
    timer--;
    timer = setTimeout(aa, timeout);
    if (times <= 0) {
      clearTimeout(timer);
    }
  }, timeout);
};

你可能感兴趣的:(JavaScript,前端,javascript)