Sobes.tech
Junior — Senior

Setting a timeout for asynchronous functions

livecode

Task condition

You need to implement a function that takes two parameters — an asynchronous function and a maximum execution time in milliseconds. The return value should be a new version of the passed function, with execution limited by the specified timeout.

  • If the original function completes faster than the set limit, the new function should return the obtained result.
  • If the execution exceeds the limit, the new function should reject the promise with the message: "Execution time limit exceeded".

Usage examples:

const fn = async (n) => {
    await new Promise(res => setTimeout(res, 100));
    return n + n;
}

asyncLimit(fn, 50); // rejected; "Execution time limit exceeded"
asyncLimit(fn, 150); // resolved; 25

const fn2 = async (a, b) => {
    await new Promise(res => setTimeout(res, 120));
    return a + b;
}

asyncLimit(fn2, 100)(1, 2); // rejected; "Execution time limit exceeded"
asyncLimit(fn2, 150)(1, 2); // resolved; 3