日常一练——实现一个定时器函数

32 阅读1分钟

1.题目描述

实现一个定时器函数 myTimer(fn, a, b), 让 fn 执行, 第一次执行是 a 毫秒后, 第二次执行是 a+b 毫秒后, 第三次是 a+2b 毫秒, 第 N 次执行是 a+Nb 毫秒后

要求: myTimer 要有返回值,并且返回值是一个函数,调用该函数,可以让 myTimer 停掉

2.举例

myTimer(() => console.log('hello world'), 1000, 2000);
// 1s 后输出 hello world
// 在过 3s 也就是 4s 后输出 hello world
// 再过 5s 也就是 9s 后输出 hello world

3.code 实现

const myTimer = (fn, a, b) => {
  let timerId;
  let count = 0;
  const _innerFn = () => {
    const time = a + count * b;
    timerId = setTimeout(() => {
      fn();
      count++;
      _innerFn();
    }, time);
  };
  _innerFn();

  return () => {
    clearTimeout(timerId);
  };
};