Day379:JS 如何实现一个 sleep/delay 函数?
qappleh opened this issue · comments
sleep 函数实现较为简单,也常作为对 Promise 的代码考察。在日常工作中,特别是 Node 写脚本时,常用它控制频率。
实现一个 sleep 函数格式如下:
type sleep = (s: number) => Promise<void>
追问:
实现一个 delay 函数格式如下,在 N 毫秒之后执行函数,并以函数结果作为返回值
function delay (func, seconds, ...args) {
}
// 在 3s 之后返回 hello, world
await delay((str) => str, 3000, 'hello, world')
// 在 3s 之后返回 hello, world,第一个函数可返回 promise
await delay((str) => Promise.resolve(str), 3000, 'hello, world')