Skip to content

Instantly share code, notes, and snippets.

@cdvillard
Created December 21, 2024 22:49
Show Gist options
  • Save cdvillard/fba98ff51aba51ab28fa55e520ef1a10 to your computer and use it in GitHub Desktop.
Save cdvillard/fba98ff51aba51ab28fa55e520ef1a10 to your computer and use it in GitHub Desktop.
"Idling" a TypeScript function
/**
* `idle` sets a timeout within a Promise that can be called within
* asynchronous contexts. This allows for the delay of an async callback.
* @param seconds
* @returns Promise<void>
*
* const asyncFunction = async (message: string) => {
* console.log("This was written now");
* await idle(10);
* console.log(message);
* };
*
* / * won't print for ten seconds * /
* asyncFunction("This should print in 10 seconds");
*/
const idle = (seconds: number): Promise<void> => {
return new Promise((resolve) => {
setTimeout(resolve, seconds * 1000);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment