一个可以暂停计时/继续计时的setTimeout

247 阅读1分钟
const mySetTimeout = (callback = () => { }, delay = 0) => {
  // 回调函数是否执行过
  let hasRun = false;
  // 执行回调的剩余等待时间
  let leftTime = delay;
  let timer = window.setTimeout(() => {
    hasRun = true;
    callback();
  }, leftTime);
  let startTime = + new Date();
  return {
    pause: () => {
      // 如果回调函数已经执行过了 那么暂停也没有意义了
      if (hasRun) {
        return;
      }
      // 获取当前时间
      const currentTime = + new Date();
      // 更新剩余时间
      leftTime = leftTime - (currentTime - startTime);
      // 清除计时器 直到continue时再生成一个新的
      window.clearTimeout(timer);
    },
    continue: () => {
      // 如果回调函数已经执行过了 那么继续也没有意义了
      if (hasRun) {
        return;
      }
      // 更新起始时间
      startTime = + new Date();
      // 生成新的计时器
      timer = window.setTimeout(() => {
        hasRun = true;
        callback();
      }, leftTime);
    }
  }
}

// 使用
const timer = mySetTimeout(() => {
  console.log('hello, world!');
}, 10000);
timer.pause();
timer.continue();