JS:创建 returns 函数,该函数在调用时等待指定的时间后执行

JS: Create function that returns function that, when invoked waits for the specified amount of time before executing

我的 objective 是:

编写一个函数延迟,它接受两个参数,一个回调和以毫秒为单位的等待时间。延迟应该 return 一个函数,当被调用时在执行之前等待指定的时间量。提示 - 研究 setTimeout();

我试过下面的代码:

const delay = (inputFunc, waitTime, ...args) => { 

  return function () {
    return setTimeout(inputFunc(), waitTime, ...args)
  }
}

// UNCOMMENT THE CODE BELOW TO TEST DELAY
let count = 0;

const delayedFunc = delay(() => count++, 1000);
delayedFunc();

console.log(count);                                                  // should print '0'

setTimeout(() => console.log(count), 1000); // should print '1' after 1 second

我收到错误:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function at setTimeout (timers.js:390:11)

我做错了什么?答案应该是什么?

setTimeout(inputFunc(), waitTime, ...args)

这意味着 "immediately call inputFunc(), then pass its result in as the first parameter to setTimeout (along with waitTime and args)"。相反,你想要:

setTimeout(inputFunc, waitTime, ...args)  

另一种选择是创建一个附加函数,该函数将调用 inputFunc,特别是当超时结束时您需要做额外的事情。例如:

setTimeout(() => { 
  // do some cleanup stuff related to delay
  inputFunc();
}, waitTime, ...args);