Async function timeout
MediumWrite asyncTimeout(fn, delay) function that takes an async function and timeout duration in milliseconds.
Requirements:
- Returns a new function with time limit
- If function completes in time - returns its result
- If exceeds timeout - rejects with "Timeout exceeded" error
- Must pass all arguments to the original function
Example:
const slowFn = async (n) => {
await sleep(1000);
return n * 2;
};
const fastFn = asyncTimeout(slowFn, 500);
await fastFn(5); // Error: Timeout exceededJavaScript•UTF-8
Run your code to see results.
Click the Run button above
Mobile view - please use desktop for better experience