How to simulate sleep in JavaScript


This post goes over how to simulate sleep in JavaScript.

Sleep

Function:

async function sleep(seconds) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, seconds * 1000);
  });
}

Usage

Example:

(async () => {
  console.log('Start');
  await sleep(5); // sleep 5 seconds
  console.log('End');
})();

Demo

Replit:



Please support this site and join our Discord!