async timeout in typescript

To create an async timeout in TypeScript, you can use a combination of setTimeout and Promises.

You can create a function that takes in a time in milliseconds as an argument and returns a Promise that resolves after that time has passed. Here's an example implementation:

index.ts
async function asyncTimeout(ms: number): Promise<void> {
  return new Promise<void>((resolve) => {
    setTimeout(() => {
      resolve();
    }, ms);
  });
}
159 chars
8 lines

You can use this function in an async/await block to set a timeout. Here's an example:

index.ts
async function asyncFunctionWithTimeout() {
  const timeoutMs = 5000; // timeout after 5 seconds
  try {
    await Promise.race([
      asyncTimeout(timeoutMs),
      // your async function or promise here
    ]);
    // the async function or promise resolved before the timeout
  } catch (error) {
    // handle timeout error here
  }
}
338 chars
13 lines

Inside the Promise.race method, we pass in an array of Promises. The first Promise to resolve or reject will be used. In this case, if the async function or promise takes longer than the timeout, the asyncTimeout Promise will resolve and the code flow will go to the catch block where you can handle the timeout error.

gistlibby LogSnag