async await wrapper for the standar settimeout function in typescript

Here's one way to create an async/await wrapper for the setTimeout function in TypeScript:

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

This function takes a number of milliseconds to delay for, and returns a promise that resolves with void after the specified delay.

To use this function, simply await its return value:

index.ts
async function myFunction() {
  console.log('Before delay');
  await delay(1000);
  console.log('After delay');
}
114 chars
6 lines

This will log "Before delay" to the console, wait for 1 second, and then log "After delay".

gistlibby LogSnag