JavaScript Interview Question #196

How would you implement a timeout for a Promise-based operation?

Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

A timeout can be modeled by racing the operation against a Promise that rejects after a specified delay. However, Promise.race alone does not cancel the underlying operation; the original work may continue.

Detailed Explanation

A timeout can be modeled by racing the operation against a Promise that rejects after a specified delay. However, Promise.race alone does not cancel the underlying operation; the original work may continue.

For APIs that support cancellation, such as fetch with AbortController, combine the timeout with real cancellation so resources are not unnecessarily consumed after the timeout expires.

Code Example

async function fetchWithTimeout(
    url,
    milliseconds
) {
    const controller = new AbortController();

    const timer = setTimeout(
        () => controller.abort(),
        milliseconds
    );

    try {
        const response = await fetch(url, {
            signal: controller.signal
        });

        return response;
    } finally {
        clearTimeout(timer);
    }
}

const response =
    await fetchWithTimeout("/api/data", 5000);