前端面试题 - 50. 实现一个函数, 可以间隔输出

387 阅读1分钟

可以使用 setInterval 和 clearInterval 实现间隔输出的功能,具体实现如下:

function createRepeat(fn, repeat, interval) {
  let count = 0;
  const timer = setInterval(() => {
    fn();
    count++;
    if (count === repeat) {
      clearInterval(timer);
    }
  }, interval);
}
const fn = createRepeat(() => console.log('helloWorld'), 3, 4000);
// 输出:
// helloWorld (4秒后)
// helloWorld (4秒后)
// helloWorld (4秒后)

在 createRepeat 函数中,首先定义了一个计数器 count,用于记录已经输出了几次。然后使用 setInterval 定时器来间隔执行 fn 函数,并在每次执行时将计数器加 1。当计数器等于 repeat 时,说明已经输出了指定次数,此时使用 clearInterval 终止定时器。在调用 createRepeat 函数时,传入的 fn 参数是一个匿名函数,用于输出指定的字符串。同时指定了 repeat 和 interval 参数,分别表示输出次数和输出间隔时间。