What is the JavaScript version of sleep()? [All Methods]

JavaScript does not have a built-in ‘sleep()‘ function that can be used to pause the execution of code for a specific amount of time. However, there are a few ways you can achieve a similar effect.

One way to pause the execution of code for a specific amount of time is to use the ‘setTimeout()function. This function takes a callback function and a time in milliseconds as arguments, and it will execute the callback after the specified time has passed. For example:

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

async function delay() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later');
}

delay();

This code will print “Taking a break…” to the console, pause for two seconds, and then print “Two seconds later” to the console.

Another way to pause the execution of code is to use the ‘async‘ / ‘await‘ syntax, which allows you to write asynchronous code that looks and behaves like synchronous code. For example:

async function delay() {
  console.log('Taking a break...');
  await new Promise(resolve => setTimeout(resolve, 2000));
  console.log('Two seconds later');
}

delay();

This code will have the same behavior as the previous example.

It’s important to note that these methods do not actually “sleep” or pause the JavaScript engine itself. Instead, they schedule a callback function to be executed after a certain amount of time has passed, allowing the JavaScript engine to continue running and executing other code in the meantime.

RELATED : How can I remove a specific item from an array? [Javascript, Python , C++]

Leave a Comment