Description

When making network requests, sometimes a server may respond too slowly or not at all.
If your application keeps waiting indefinitely, it can freeze or create a bad user experience.

To prevent this, developers use a timeout mechanism — which automatically cancels a request if it takes too long.

In this challenge, you’ll build a version of fetch that automatically aborts requests exceeding a given time limit.


Your Task

Implement a function fetchWithTimeOut(url, time) that returns a promise which:

  • Initiates a fetch() call to the given URL.
  • Waits for a maximum of time milliseconds.
  • Rejects the promise and aborts the request if it doesn’t finish in time.
  • Resolves normally if the fetch completes before the timeout.

Method

Function

Description

fetchWithTimeOut(url, time)

Performs a fetch request with a timeout limit. If the request takes longer than time milliseconds, it aborts and rejects.


Example

Input

const response1 = await fetchWithTimeOut("https://example.com/fast", 2000);
console.log("✅ Fast request completed");

const response2 = await fetchWithTimeOut("https://example.com/slow", 500);
console.log("❌ This will not appear");

Expected Output

✅ Fast request completed
❌ Request timed out

Expected Behavior

  • Aborts the request if it exceeds the timeout period
  • Rejects with an error when the timeout is reached
  • Resolves with the fetch response if it completes in time
  • Each call works independently (no shared state)

Hints

Hints 1

Use AbortController to cancel the fetch request.

Hints 2

Use setTimeout() to trigger the abort after the specified time.

Hints 3

Remember to clear the timeout if the fetch finishes first.