← All Exercises

Promise Timeout with Timer Cleanup

intermediatejavascript~15min

Background

Network calls can hang, so applications race them against a deadline. A correct implementation also releases the timer, otherwise a slow process can be kept alive or a late rejection can surface after success.

Problem

Implement withTimeout(promise, ms). The returned promise resolves with the original value when the input settles first, rejects with a TimeoutError when the deadline passes first, and clears the timer whenever the input settles. Original rejections must pass through unchanged.

Input

A JSON object with delay, limit, optional value, and optional reject plus message.

Output

One line describing the outcome: resolved:<value> for success or rejected:<TimeoutError|message> for failure.

Sample tests

Sample 1

Input: {"delay":20,"limit":100,"value":"ok"}
Expected: resolved:ok

Sample 2

Input: {"delay":50,"limit":10}
Expected: rejected:TimeoutError

Sample 3

Input: {"delay":5,"limit":100,"reject":true,"message":"boom"}
Expected: rejected:boom

Your solution

Learning objective

Practice Promise.race-style timeout logic, settlement cleanup, and custom error types for async workflows.