timeout

The timeout function wraps a function with a timeout. If the function does not complete within the specified time, the promise will be rejected.

1.
/**
2.
* The timeout function wraps a function with a timeout. If the function does not complete within the specified time, the promise will be rejected.
3.
**/
4.
const timeout = <Return, Err>(
5.
fn: (...args: any[]) => Return,
6.
time: number,
7.
errCb?: (...args: any[]) => Err,
8.
): ((...args: any[]) => Promise<Return>) => {
9.
return (...args: any[]) => {
10.
return new Promise<any>((resolve, reject) => {
11.
const timer = setTimeout(() => {
12.
if (errCb) reject(errCb(...args));
13.
else {
14.
reject(new Error('Function timed out'));
15.
}
16.
}, time);
17.
18.
// Wrap fn call in Promise.resolve to handle both sync and async functions
19.
Promise.resolve(fn(...args))
20.
.then((result: Return) => {
21.
clearTimeout(timer);
22.
resolve(result);
23.
})
24.
.catch((err: Err) => {
25.
clearTimeout(timer);
26.
reject(err);
27.
});
28.
});
29.
};
30.
};
31.
32.
export default timeout;

1. Installtion

npx @jrtilak/lazykit add timeout

2. Parameters

  • fn ((...args: any[]) => Return)
    The function to wrap with a timeout. This function can be synchronous or asynchronous.

  • time (number)
    The time (in milliseconds) before the function times out.

  • errCb (optional) ((...args: any[]) => Err)
    An optional callback function that is invoked if the timeout occurs. It receives the same arguments as fn.

3. Returns

  • (...args: any[]) => Promise<Return>
    Returns a function that, when called, returns a promise. The promise resolves with the result of fn if it completes within the specified time, or it rejects with an error if the function times out.

4. Type Parameters

  • Return
    The return type of the function fn.

  • Err
    The type of the error returned by the errCb callback, if provided.

5. Usage

1. Synchronous Function Example:

This example wraps a synchronous function with a timeout.

1.
import timeout from "@/utils/timeout";
2.
3.
function syncFunction() {
4.
return "Quick result";
5.
}
6.
7.
const timedSyncFunction = timeout(syncFunction, 500); // Timeout set to 500 ms
8.
9.
timedSyncFunction()
10.
.then((result) => console.log(result)) // Logs: "Quick result"
11.
.catch((error) => console.error(error.message));

In this case, syncFunction completes immediately, so timedSyncFunction resolves successfully before the timeout.

2. Asynchronous Function with Error Callback:

This example demonstrates an asynchronous function that might exceed the timeout. An error callback onTimeout provides custom error handling.

1.
import timeout from "@/utils/timeout";
2.
3.
async function fetchData() {
4.
return new Promise((resolve) => setTimeout(() => resolve("Data received"), 3000)); // 3 seconds delay
5.
}
6.
7.
const onTimeout = () => "Fetching data timed out"; // Custom error message
8.
9.
const timedFetchData = timeout(fetchData, 1000, onTimeout); // Timeout set to 1 second
10.
11.
timedFetchData()
12.
.then((data) => console.log(data))
13.
.catch((error) => console.error(error)); // Logs: "Fetching data timed out"

Here, fetchData takes 3 seconds, but timedFetchData has a 1-second timeout. When the timeout is reached, onTimeout is called, and the promise is rejected with "Fetching data timed out".

These examples illustrate how timeout can be used with both synchronous and asynchronous functions and provide custom error handling with errCb.