asynchronous wrapper for the standard javascript settimeout function in typescript

Here's an example of an asynchronous wrapper function for the standard JavaScript setTimeout function in TypeScript using Promises:

index.ts
function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
106 chars
4 lines

This function takes in a number of milliseconds (ms) as the argument and returns a promise that resolves after the specified time has elapsed.

To use this function, you can simply call it and then chain on the .then method to execute code after the delay:

index.ts
console.log('Before delay');

delay(1000).then(() => {
  console.log('After delay');
});

console.log('End of script');
120 chars
8 lines

This will output the following:

index.ts
Before delay
End of script
After delay
39 chars
4 lines

Note how the console logs are output in the expected order, even though there's a delay of 1000ms in between them. This is because the delay function is an asynchronous wrapper around setTimeout, allowing other code to be executed while waiting for the delay to finish.

gistlibby LogSnag