LeetCode 题解工作台

睡眠函数

请你编写一个异步函数,它接收一个正整数参数 millis ,并休眠 millis 毫秒。要求此函数可以解析任何值。 请注意 ,实际睡眠持续时间与 millis 之间的微小偏差是可以接受的。 示例 1: 输入: millis = 100 输出: 100 解释: 在 100ms 后此异步函数执行完时返回…

category

0

题型

code_blocks

2

代码语言

hub

0

相关题

当前训练重点

简单 · Sleep core interview pattern

bolt

答案摘要

async function sleep(millis: number): Promise<void> { return new Promise(r => setTimeout(r, millis));

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Sleep core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你编写一个异步函数,它接收一个正整数参数 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
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * @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
 */
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

睡眠函数题解:Sleep core interview pa… | LeetCode #2621 简单