LeetCode 题解工作台
睡眠函数
请你编写一个异步函数,它接收一个正整数参数 millis ,并休眠 millis 毫秒。要求此函数可以解析任何值。 请注意 ,实际睡眠持续时间与 millis 之间的微小偏差是可以接受的。 示例 1: 输入: millis = 100 输出: 100 解释: 在 100ms 后此异步函数执行完时返回…
0
题型
2
代码语言
0
相关题
当前训练重点
简单 · Sleep core interview pattern
答案摘要
async function sleep(millis: number): Promise<void> { return new Promise(r => setTimeout(r, millis));
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Sleep core interview pattern 题型思路
题目描述
请你编写一个异步函数,它接收一个正整数参数 millis ,并休眠 millis 毫秒。要求此函数可以解析任何值。
请注意,实际睡眠持续时间与 millis 之间的微小偏差是可以接受的。
示例 1:
输入:millis = 100
输出:100
解释:
在 100ms 后此异步函数执行完时返回一个 Promise 对象
let t = Date.now();
sleep(100).then(() => {
console.log(Date.now() - t); // 100
});
示例 2:
输入:millis = 200 输出:200 解释:在 200ms 后函数执行完时返回一个 Promise 对象
提示:
1 <= millis <= 1000
解题思路
方法一
/**
* @param {number} millis
* @return {Promise}
*/
async function sleep(millis) {
return new Promise(r => setTimeout(r, millis));
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidates should demonstrate familiarity with asynchronous JavaScript and promise handling.
- question_mark
Ensure candidates discuss potential deviations when using setTimeout for precise timing.
- question_mark
Look for candidates to handle edge cases and guarantee resolution within a given time range.
常见陷阱
外企场景- error
Using setTimeout incorrectly, such as not wrapping it in a promise.
- error
Misunderstanding the non-deterministic nature of timing in JavaScript and expecting precise resolution.
- error
Not handling edge cases where millis is extremely small or close to the upper constraint.
进阶变体
外企场景- arrow_right_alt
Implement a sleep function using async/await.
- arrow_right_alt
Modify the problem to accept an array of millis values, where the function sleeps for each value in the array sequentially.
- arrow_right_alt
Extend the problem to include a timeout option where the function rejects if the sleep time exceeds a certain threshold.