Sobes.tech
Middle+

Implement a function withTimeout that takes a function and a time (milliseconds) and returns a new function. If the original function does not complete within the specified time, the promise should be rejected.

sobes.tech AI

Answer from AI

The withTimeout function should accept a function that returns a promise and a time in milliseconds. It returns a new function that, when called, runs the original function and a timer simultaneously. If the original function does not complete within the specified time, the promise is rejected with a timeout error.

Example implementation in JavaScript:

function withTimeout(fn, ms) {
  return function(...args) {
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        reject(new Error('Timeout'));
      }, ms);

      fn(...args)
        .then(result => {
          clearTimeout(timer);
          resolve(result);
        })
        .catch(err => {
          clearTimeout(timer);
          reject(err);
        });
    });
  };
}

// Usage:
// const fetchWithTimeout = withTimeout(fetch, 5000);
// fetchWithTimeout('https://example.com').then(...).catch(...);