How to sleep in JavaScript

How to sleep in JavaScript

In JavaScript, you can use the setTimeout function to pause the execution of your code for a certain amount of time. This can be used to simulate the act of sleeping, although it is not an actual sleep function. Here is an example of how you might use setTimeout to make your code "sleep" for a certain amount of time:

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

async function demo() {
  console.log("Starting");
  await sleep(2000);
  console.log("Finishing");
}

demo();

In this example, the sleep function uses setTimeout to pause the code for a specified number of milliseconds (in this case, 2000 milliseconds, or 2 seconds). The await keyword is used to wait for the sleep function to resolve before continuing with the next line of code. This allows us to pause the code and simulate the act of sleeping.

How to sleep in JavaScript without Promise and async

Here is an example of how you might use a callback function with setTimeout to simulate the act of "sleeping" in JavaScript:

function sleep(ms, callback) {
  setTimeout(function() {
    callback();
  }, ms);
}

function demo() {
  console.log("Starting");
  sleep(2000, function() {
    console.log("Finishing");
  });
}

demo();

In this example, the sleep function uses setTimeout to pause the code for a specified number of milliseconds (in this case, 2000 milliseconds, or 2 seconds). When the specified time has elapsed, the setTimeout function will execute the callback function that is passed to it. In this case, the callback function simply logs a message to the console.

This approach allows you to abstract the act of "sleeping" into a separate function, and pass in a callback to be executed when the sleep time has elapsed. This can be useful if you need to perform multiple actions after the sleep time has elapsed, or if you want to use the same sleep function in multiple places in your code.