In this article, we will discuss how to implement a random sleep in JavaScript.

Defining the sleep method

In javascript we can simulate the sleep functionality by using the setTimeout. In the below example, we defined our own sleep function which takes the duration as the parameter. This specifies the number of milliseconds to wait before continuing.

function sleep(duration) {
  return new Promise(resolve => setTimeout(resolve, duration));
}

The setTimeout() method in the above function delay the execution of the resolve function by the specified duration. The resolve function is called only after the specified duration has elapsed, which indicates that the sleep is complete.

Generating the random duration for sleep

Now, we need to generate a random duration for the sleep. Using the Math.random() method to generate a pseudo random number between 0 and 1, and then multiply it by a maximum duration to get a random duration.

In the below example, we set the maximum duration to 5000 milliseconds or 5 seconds. Within this range, we generate the random sleep duration.

const maxDuration = 5000; // 5 seconds
const randomDuration = Math.random() * maxDuration;

Calling the sleep with random duration

Now, we can the sleep function which we have defined in the above example with the random duration to perform the random sleep.

Following is the complete code on how to do random sleep in javascript

function sleep(duration) {
  return new Promise(resolve => setTimeout(resolve, duration));
}

const maxDuration = 5000; // 5 seconds
const randomDuration = Math.random() * maxDuration;

console.log("Before sleep");
await sleep(randomDuration); // wait for 2 seconds
console.log("After sleep");

In the above example, we define a sleep function that returns a Promise that resolves after the specified duration using setTimeout().

We print message before and after calling the sleep function random delay. The await keyword is used to wait for the sleep function to complete before logging the message “After sleep“.

Categorized in:

Tagged in: