JavaScript is asynchronous by design, so implementing a sleep function can be tricky.

The closest you can get to pausing execution for some time is by using Promise and await.

The function sleep accepts a single argument ms and returns a Promise that resolves in ms milliseconds.

const sleep = (ms) => new Promise((resolve, reject) => setTimeout(() => resolve(), ms));

You can test the sleep function in your browser console with the following code.

console.log(1);
await sleep(1000);
console.log(2);

This will add a one-second delay (1000 ms) between the console logs.