Pause Sleep Wait Delay In Javascript – Plus BETTER Alternatives

Welcome to a quick tutorial on how to pause or sleep in Javascript. Need to wait or do a delayed script?

There are no native implementations of pause or sleep in Javascript.

  1. But we can emulate sleep or wait using a timestamp and while loop.
    • var now = Date.now();
    • var end = now + MILISECONDS;
    • while (now < end) { now = Date.now(); }
  2. Or delay execution using a timer.
    • setTimeout(FUNCTION, MILISECONDS);
  3. In async functions (or NodeJS), we can simulate wait by creating an empty promise placed on a timer.
    • await new Promise(res => { setTimeout(res, MILISECONDS); });

That covers the basics, but let us walk through more examples in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes JS Pause Better Alternatives
Useful Bits & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

JAVASCRIPT PAUSE

All right, let us now begin with the ways we can emulate sleep or pause in Javascript first… For the folks who just want to do it for some reason.

 

PAUSE OR WAIT USING WHILE LOOP

1-timer.js
// (A) DUMMY SLEEP FUNCTION
var sleep = function (ms) {
  let now = Date.now(), end = now + ms;
  while (now < end) { now = Date.now(); }
};

// (B) TEST RUN
console.log("Foo");
sleep(1000); // WAIT 1 SECOND
console.log("Bar");

Yes, this is a very traditional method, and it’s that simple. There is no native sleep function in Javascript, so we just make it run a dummy while loop until the time is up.

 

DELAYED SCRIPT

2-timer.js
// (A) DO SOMETHING FIRST
var data = ["Apple"];
console.log(data); // ["Apple"]

// (B) DELAY USING TIMER - RUN THIS 2 SECS LATER
setTimeout(() => {
  data.push("Cow"); // ["Apple", "Banana", "Cow"]
  console.log(data);
}, 2000);

// (C) TAKE NOTE - THE REST WILL CONTINUE TO RUN!
dummy.push("Banana");
console.log(dummy); // ["Apple", "Banana"]

This is another old-school method that you will see everywhere on the Internet. We can delay the execution of a block of code using the good old timer – setTimeout(). But please take note that timers do not block the rest of the script from running; Timers do not “sleep”, but “delay” a block of code.

 

 

THE BETTER ALTERNATIVES

For goodness sake, the Stone Age of the Internet is long over. Javascript has evolved a lot over the years, and there are various modern mechanics to deal with “wait for the script to finish”, or “wait for things to load” – Welcome to async functions, promises, and events.

 

ASYNCHRONOUS FUNCTIONS

3-async.js
// (A) ASYNC FUNCTION - DO SOME MASSIVE PROCESSING
var dummy = async function (num) {
  for (i=1; i<999999; i++) { num++; }
  return num;
};

// (B) TEST RUN
// (B1) CALL THE ASYNC FUNCTION
dummy(1)
 
// (B2) DO THIS WHEN THE ASYNC FUNCTION IS DONE
.then(result => {
  console.log("Dummy is done.");
  console.log(result);
});
 
// (C) ASYNC FUNCTIONS RUN IN PARALLEL, THE REST WILL CONTINUE TO RUN
console.log("Foo bar!");

For you guys who are thinking along the lines of “wait for massive processing to complete”, do consider adopting asynchronous functions instead.

  • async function () is just like a “normal function”.
  • But we append a then block to collect the results and specify what to do when it is complete.

Yes, asynchronous functions run in parallel, they do not freeze nor block the rest. It automatically calls the then block when it is done. No more foolish “wait and see if the processing is done”.

 

 

WAITING IN ASYNC FUNCTIONS & NODEJS

4-async-await.js
async function test () {
  console.log("foo");
  await new Promise(res => { setTimeout(res, 1000); });
  console.log("bar");
}
test();

Still need to wait in an asynchronous function? This seems to the “accepted solution” in most forums and website – We simply await for an empty promise that is placed on a timer.

 

EVENTS

5-events.js
window.addEventListener("DOMContentLoaded", function(){
  // (A) CREATE ELEMENT
  var img = document.createElement("img");

  // (B) ATTACH EVENT LISTENER
  img.addEventListener("load", function(){
    console.log("Image Loaded!");
  });

  // (C) SET SOURCE & ADD TO PAGE
  document.body.appendChild(img);
  img.src = "cow.jpg";
});

Has the image loaded? Has the video loaded? Is this or that ready? Well, there are a ton of events in Javascript to handle that. Don’t have to create a “wait and check” timer.

 

 

CUSTOM EVENTS

6-custom-events.js
// (A) THE FUNCTION
var foo = function () {
  // (A1) DO PROCESSING
  let num = 8;
  for (let i=0; i<999999; i++) { num++; }

  // (A2) DISPATCH CUSTOM EVENT
  document.dispatchEvent(new Event("FOODONE"));
};

// (B) ATTACH LISTENERS
document.addEventListener("FOODONE", evt => {
  console.log(evt);
  console.log(this);
});

// (C) GO!
foo();

Lastly, we can also manually dispatch our own custom events for “this is done” or “that is ready”.

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

How To Pause Or Wait In Javascript (click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *