Sleep in JavaScript - delay between actions

Viewed 113241

Is there a way I can do a sleep in JavaScript before it carries out another action?

Example:

var a = 1 + 3;
// Sleep 3 seconds before the next action here.
var b = a + 4;
15 Answers

You can use setTimeout to achieve a similar effect:

var a = 1 + 3;
var b;
setTimeout(function() {
    b = a + 4;
}, (3 * 1000));

This doesn't really 'sleep' JavaScript—it just executes the function passed to setTimeout after a certain duration (specified in milliseconds). Although it is possible to write a sleep function for JavaScript, it's best to use setTimeout if possible as it doesn't freeze everything during the sleep period.

Another way to do it is by using Promise and setTimeout (note that you need to be inside a function and set it as asynchronous with the async keyword) :

async yourAsynchronousFunction () {

    var a = 1+3;

    await new Promise( (resolve) => {
        setTimeout( () => { resolve(); }, 3000);
    }

    var b = a + 4;

}

Here's a very simple way to do it that 'feels' like a synchronous sleep/pause, but is legit js async code.

// Create a simple pause function
const pause = (timeoutMsec) => new Promise(resolve => setTimeout(resolve,timeoutMsec))

async function main () {
    console.log('starting');
    // Call with await to pause.  Note that the main function is declared asyc
    await pause(3*1000)
    console.log('done');
}

You can use plain javascript, this will call your function/method after 5 seconds:

setTimeout(()=> { your_function(); }, 5000);

You can use setTimeout to call a callback after a specified amount of time:

setTimeout(() => {
    console.log('Called after 1 second');
}, 1000);

If you want to use setTimeout as a promise, you can do this:

const delay = milliseconds => new Promise(resolve => { setTimeout(resolve, milliseconds); });

await delay(1000);

console.log('Called after 1 second');

Since Node.js 16, this functionality is also built-in:

import {setTimeout as delay} from 'node:timers/promises';

await delay(1000);

console.log('Called after 1 second');

If you want a synchronous delay in Node.js or in the browser outside of the main thread, you can use Atomics.wait:

const delay = milliseconds => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);

await delay(1000);

console.log('Called after 1 second');

Here's a re-write and a demo of a Promise-based sleep() using call to setTimeout(). It also demos a regular call to setTimeout().

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

console.log("Synchronous call");
sleep(2000)
.then(() => console.log("Asynchronous call"));

Image of its run on Repl.it

function sleep(ms) {
    return new Promise(resolve => setTimeout(() => resolve(), ms))
}
console.log("Synchronous call 1");

sleep(4000)
 .then(() => console.log("Asynchronous call 1"));

sleep(2000)
 .then(() => console.log("Asynchronous call 2"));

console.log("Synchronous call 2");

sleep(3000)
 .then(() => console.log("Asynchronous call 3"));

console.log("Synchronous call 3");

sleep(5000)
 .then(() => console.log("Asynchronous call 4"))
 .then(
   sleep(7000)
    .then(()=>console.log("Asynchronous call 5"))
)

console.log("Synchronous call 4");

setTimeout(() => {console.log("Asynchronous call 6")}, 8000);
console.log("Synchronous call 5");

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

async function myFunction(){  // Function Must be async.
  console.log("First Console")
  await delayer(2000);    // This Will Stop The Code For 2 Seconds
  console.log("Second Console")
}


myFunction()

For what is worth

  isPause = true;
  setTimeout(()=>{isPause=false},2000);
  while (!isPause) {
    // delay for 2 seconds
  }
    

This is my model that shows how to "sleep" or "DoEvents" in javascript using a generator function (ES6). Commented code:

<html>
<head>
<script>
  "use strict"; // always
  // Based on post by www-0av-Com https://stackoverflow.com/questions/3143928
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
  var divelt, time0, globaln = 0; // global variables
  var MainGenObj = Main(); // generator object = generator function()
window.onload = function() {
  divelt = document.getElementsByTagName("body")[0]; // for addline()
  addline("typeof Main: " + typeof Main);
  addline("typeof MainDriver: " + typeof MainDriver);
  addline("typeof MainGenObj: " + typeof MainGenObj);
  time0 = new Date().valueOf(); // starting time ms
  MainDriver(); // do all parts of Main()
}
function* Main() { // this is "Main" -- generator function -- code goes here
  // could be loops, or inline, like this:

  addline("Part A, time: " + time() + ", " + ++globaln); // part A
  yield 2000;                    // yield for 2000 ms (like sleep)

  addline("Part B, time: " + time() + ", " +  ++globaln); // part B
  yield 3000;                    // yield for 3000 ms (or like DoEvents)

  addline("Part Z, time: " + time() + ", " +  ++globaln); // part Z (last part)
  addline("End, time: " + time());
}
function MainDriver() { // this does all parts, with delays
  var obj = MainGenObj.next(); // executes the next (or first) part of Main()
  if (obj.done == false) { // if "yield"ed, this will be false
    setTimeout(MainDriver, obj.value); // repeat after delay
  }
}
function time() { // seconds from time0 to 3 decimal places
  var ret = ((new Date().valueOf() - time0)/1000).toString();
  if (ret.indexOf(".") == -1) ret += ".000";
  while (ret.indexOf(".") >= ret.length-3) ret += "0";
  return ret;
}
function addline(what) { // output
  divelt.innerHTML += "<br />\n" + what;
}
</script>
</head>
<body>
<button onclick="alert('I\'m alive!');"> Hit me to see if I'm alive </button>
</body>
</html>

I know this question is old, but if someone is searching for this, there's a cleaner way of ACTUALLY sleeping in javascript using promises

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

const run = async () => {
    while(true){
        console.log("yay1")
        await sleep(3000)
        console.log("next action")
    }
}

run()

This will always have a 3 seconds pause between the first log and second log

What happens here is,

  1. Using await the code execution of JavaScript pauses until the promise is resolved.

  2. The promise will be resolved when the resolver gets fired. The resolver will be fired when setTimeout is executed.

  3. setTimeout will be executed after a given duration in milliseconds.

Related