qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!

Home Page:https://github.com/qappleh/Interview

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Day379:JS 如何实现一个 sleep/delay 函数?

qappleh opened this issue · comments

commented

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')