javascript函数间隔输出(面试题)

265 阅读1分钟

实现一个函数,可以定义传递进去的函数,执行次数与间隔,后再次调用传递参数后执行

function createRepeat(fn, repeat, interval) {}
const fn = createRepeat(console.log, 3, 4);
fn('helloWorld'); // 每4秒输出一次helloWorld, 输出3次

思路: 因为需要传递要执行函数、执行次数与间隔后再次调用时执行,所以需要返回一个函数。函数内部使用递归的形式实现,从需要执行的次数到1的位置后终止递归

function createRepeat(fn, repeat, interval) {
  return (val) => {
    if (repeat > 0) {
      setTimeout(() => {
        fn(val);
        repeat--;
        createRepeat(fn, repeat, interval)(val);
      }, interval * 1000);
    }
  };
}

const fn = createRepeat(console.log, 3, 4);

fn("helloWorld");

最终: 结果打印

image.png