Here's an example of an asynchronous wrapper function for the standard JavaScript setTimeout
function in TypeScript using Promises:
index.ts106 chars4 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.ts120 chars8 lines
This will output the following:
index.ts39 chars4 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