Promise Time Limit - Problem

Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. The function fn takes arguments provided to the time limited function.

The time limited function should follow these rules:

  • If the fn completes within the time limit of t milliseconds, the time limited function should resolve with the result.
  • If the execution of the fn exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded".

Input & Output

Example 1 — Function Completes in Time
$ Input: fn = async () => { await new Promise(res => setTimeout(res, 50)); return 'result'; }, t = 100
Output: 'result'
💡 Note: Function takes 50ms to complete, which is within the 100ms limit, so it resolves with 'result'
Example 2 — Function Times Out
$ Input: fn = async () => { await new Promise(res => setTimeout(res, 200)); return 'result'; }, t = 100
Output: Time Limit Exceeded
💡 Note: Function takes 200ms but timeout is 100ms, so the timeout promise rejects first with 'Time Limit Exceeded'
Example 3 — Immediate Resolution
$ Input: fn = async () => 42, t = 50
Output: 42
💡 Note: Function resolves immediately with 42, well within the 50ms timeout

Constraints

  • 0 ≤ t ≤ 1000
  • fn returns a promise

Visualization

Tap to expand
Promise Time Limit INPUT fn = async () => { await new Promise( res => setTimeout(res, 50) ); return 'result'; } t = 100ms Time Limit Timeline: 0ms 50ms fn done 100ms limit 50ms < 100ms (within limit) ALGORITHM STEPS 1 Create Timer Promise setTimeout rejects after t ms 2 Execute fn(...args) Run original async function 3 Promise.race() Race fn vs timer promise 4 Return Winner First settled promise wins // Promise.race approach Promise.race([ fn(...args), new Promise((_, rej) => setTimeout(() => rej('Time Limit...'), t) ) ]) FINAL RESULT Promise.race() Result fn Promise 50ms - WINS! Timer 100ms fn completed first! 50ms < 100ms OUTPUT 'result' OK - Resolved! If fn took 150ms instead: "Time Limit Exceeded" Key Insight: Promise.race() returns the first promise to settle. By racing the original function against a timer, we create a timeout mechanism: if fn finishes first --> resolve with result; if timer fires first --> reject. TutorialsPoint - Promise Time Limit | Promise.race Implementation
Asked in
Meta 25 Google 20
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen