MuTasim

sleep.

Another day, I was sitting and coding an algorithms visualizer project. Then, I reached a point where I needed a delay between iterations in my loop to visualize the project properly. Without a sleep function, I couldn't observe the results. So, I added the sleep function, and voilà, everything became smooth and good. Later on, I found myself needing this function in other projects. Let's take a look at the sleep function now.

./lib/utils.js
export const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

How does it work?

The sleep function utilizes the built-in setTimeout function to introduce a delay in the execution of your code. It takes a single argument, ms (milliseconds), which determines the duration of the sleep. The function returns a Promise, allowing you to easily incorporate it into your asynchronous workflows.

./examples/example.ts
import { sleep } from "@/lib/utils";

async function performAsyncTask(): void {
    console.log("Task starting...");
    
    // Introducing a 2-second delay using the sleep function
    await sleep(2000);
    
    console.log("Task completed after 2 seconds.");
}

performAsyncTask();

In practice, incorporating a lightweight sleep function can be beneficial for scenarios where you need to introduce delays in your asynchronous code. Whether you're working with animations, simulating network latency, or handling timing-sensitive tasks, having a minimal and efficient sleep function at your disposal can be a valuable asset.