TypeScript Idling — await Sleep()

Lars Holdaas
2 min readNov 9, 2021

Sometimes you just want to delay execution for a brief moment. Let’s take a look at an easy way to set up an idling function.

This solution also applies to Javascript.

A common way of delaying execution, as well as forcing asynchronicity, is to use the setTimeout() function. While this is familiar enough for most Javascript and Typescript developers, this solution offers a handful of issues:

  • It is quite verbose for what it does
  • The value definition for the length of the timeout comes at the end of the code, often requiring skipping through sometimes very long pieces of code before being available to a reader of the algorithm
  • Can lead to the same problem that Promises has which caused async/await to become popular; infinite brackets of increasingly difficult to read logic

So, how can we do this in a short-hand manner using async/await?

sleep()

We define the sleep function as follows:

export const sleep = async (waitTime: number) =>
new Promise(resolve =>
setTimeout(resolve, waitTime));

Summarized, we create an asynchronous function (marking it as asynchronous by using async ) that creates a Promise which will automatically resolve after waitTime has…

--

--

Lars Holdaas
Lars Holdaas

Written by Lars Holdaas

Web developer working in Japan. Passionate about maintanability and clean coding.

No responses yet