【发布时间】:2020-07-10 05:16:33
【问题描述】:
我正在创建一个延迟函数,它接受回调和等待时间(以毫秒为单位)作为参数。 delay 应该返回一个函数,该函数在被调用时会在执行前等待指定的时间量。这里我使用 setTimeout() 在执行函数之前设置一个计时器。
function delay (callback, time) {
function waitOnMe(...args) {
return setTimeout(time);
}
return waitOnMe;
}
我使用以下代码来测试上面的代码:
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
然后我得到以下输出和错误消息(注意第三个输出是在第二行出现后大约 1 秒生成的)。
0
Type Error on line callback is not a function at blob: callback is not a function
0
我想我得到这个错误是因为函数在指定的等待时间后没有从延迟返回执行回调,但我不确定。
【问题讨论】:
-
return setTimeout(time)缺少延迟参数,第一个参数是回调,第二个(这里缺少)是延迟。 -
谢谢!为清楚起见,“时间”参数旨在表示延迟。
-
参数的顺序定义了参数的类型,而不是名称。
标签: javascript