LeetCode 题解工作台

有时间限制的 Promise 对象

请你编写一个函数,它接受一个异步函数 fn 和一个以毫秒为单位的时间 t 。它应根据限时函数返回一个有 限时 效果的函数。函数 fn 接受提供给 限时 函数的参数。 限时 函数应遵循以下规则: 如果 fn 在 t 毫秒的时间限制内完成, 限时 函数应返回结果。 如果 fn 的执行超过时间限制, 限时…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

中等 · Promise Time Limit core interview pattern

bolt

答案摘要

type Fn = (...params: any[]) => Promise<any>; function timeLimit(fn: Fn, t: number): Fn {

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

请你编写一个函数,它接受一个异步函数 fn 和一个以毫秒为单位的时间 t。它应根据限时函数返回一个有 限时 效果的函数。函数 fn 接受提供给 限时 函数的参数。

限时 函数应遵循以下规则:

  • 如果 fnt 毫秒的时间限制内完成,限时 函数应返回结果。
  • 如果 fn 的执行超过时间限制,限时 函数应拒绝并返回字符串 "Time Limit Exceeded"

 

示例 1:

输入:
fn = async (n) => { 
  await new Promise(res => setTimeout(res, 100)); 
  return n * n; 
}
inputs = [5]
t = 50
输出:{"rejected":"Time Limit Exceeded","time":50}
解释:
const limited = timeLimit(fn, t)
const start = performance.now()
let result;
try {
   const res = await limited(...inputs)
   result = {"resolved": res, "time": Math.floor(performance.now() - start)};
} catch (err) {
   result = {"rejected": err, "time": Math.floor(performance.now() - start)};
}
console.log(result) // 输出结果

提供的函数设置在 100ms 后执行完成,但是设置的超时时间为 50ms,所以在 t=50ms 时拒绝因为达到了超时时间。

示例 2:

输入:
fn = async (n) => { 
  await new Promise(res => setTimeout(res, 100)); 
  return n * n; 
}
inputs = [5]
t = 150
输出:{"resolved":25,"time":100}
解释:
在 t=100ms 时执行 5*5=25 ,没有达到超时时间。

示例 3:

输入:
fn = async (a, b) => { 
  await new Promise(res => setTimeout(res, 120)); 
  return a + b; 
}
inputs = [5,10]
t = 150
输出:{"resolved":15,"time":120}
解释:
在 t=120ms 时执行 5+10=15,没有达到超时时间。

示例 4:

输入:
fn = async () => { 
  throw "Error";
}
inputs = []
t = 1000
输出:{"rejected":"Error","time":0}
解释:
此函数始终丢出 Error

 

提示:

  • 0 <= inputs.length <= 10
  • 0 <= t <= 1000
  • fn 返回一个 Promise 对象
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type Fn = (...params: any[]) => Promise<any>;

function timeLimit(fn: Fn, t: number): Fn {
    return async function (...args) {
        return Promise.race([
            fn(...args),
            new Promise((_, reject) => setTimeout(() => reject('Time Limit Exceeded'), t)),
        ]);
    };
}

/**
 * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
 * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
 */
speed

复杂度分析

指标
时间complexity depends on fn's execution and the set timeout, while space complexity is dominated by creating the wrapper and promises. Overhead is minimal and linear with argument count.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Looking for correct usage of Promise.race or equivalent time-limiting logic.

  • question_mark

    Checking that arguments are passed correctly to the original function inside the wrapper.

  • question_mark

    Observing handling of both resolved and rejected promises under time constraints.

warning

常见陷阱

外企场景
  • error

    Forgetting to reject the promise when the time limit is exceeded.

  • error

    Not forwarding arguments correctly to fn, causing unexpected behavior.

  • error

    Swallowing errors from fn instead of letting them propagate in the wrapper.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Enforce different time limits dynamically per call instead of a fixed t.

  • arrow_right_alt

    Apply the time-limiting pattern to multiple concurrent asynchronous functions.

  • arrow_right_alt

    Return additional metadata like actual elapsed time alongside the resolved value or rejection.

help

常见问题

外企场景

有时间限制的 Promise 对象题解:Promise Time Limit core… | LeetCode #2637 中等