Sobes.tech
Junior — Senior

Timeout limiter for asynchronous functions

livecode

Task condition

It is necessary to implement a wrapper function that takes two parameters – an asynchronous function and a time limit in milliseconds. The returned function should execute the original asynchronous task but not longer than the specified limit. Requirements: • If the original function completes faster than the limit, the wrapper should return the obtained result. • If execution exceeds the set limit, the wrapper should reject the promise with the message "Execution time limit exceeded".

const originalFn = async (n) => {
  await new Promise(res => setTimeout(res, 100));
  return n * n;
}
withTimeout(originalFn, 50)(5); // rejected: Execution time limit exceeded
withTimeout(originalFn, 150)(5); // resolved: 25

const sumFn = async (a, b) => {
  await new Promise(res => setTimeout(res, 120));
  return a + b;
}
withTimeout(sumFn, 100)(1, 2); // rejected: Execution time limit exceeded
withTimeout(sumFn, 150)(1, 2); // resolved: 3