3 Ways To Pause Javascript (Very Simple Examples)

Welcome to a quick tutorial on how to pause in Javascript. Bad news, there are no native implementations of pause in Javascript. But we can simulate pause, wait, sleep, or delay in Javascript via various means:

  • Loop until a certain time has passed – var now = Date.now(), end = now + 1000; while (now < end) { now = Date.now(); }
  • Delay a function using timeout – setTimeout(FUNCTION, 1000);
  • Delay the return of an async function –async function fn () { await new Promise(res => setTimeout(res, 1000)); }

That covers the quick basics but read on for the detailed explanation – Also, for a possibly better solution.

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

JAVASCRIPT PAUSE

All right, let us get into the examples of possible ways to pause in Javascript.

 

TUTORIAL VIDEO

 

METHOD 1) TIMESTAMP WHILE LOOP

1-time-loop.html
// (A) DO SOMETHING
console.log("First");
 
// (B) WAIT 2 SECONDS (2000 MS)
var now = Date.now(),
    end = now + 2000;
while (now < end) { now = Date.now(); }
 
// (C) PROCEED
console.log("Second");

For those who are lost:

  • console.log("First") will run first.
  • now is set to the current timestamp, and end is 2 seconds from now.
  • while (now < end) { now = Date.now(); } will loop endlessly for 2 seconds, that’s our “pause”.
  • console.log("Second") will run after 2 seconds.

 

 

METHOD 2) FUNCTION TIMEOUT

2-timeout.html
// (A) FUNCTION TO RUN AFTER DELAY
function demo () { console.log("Second"); }
 
// (B) DO SOMETHING
console.log("First");
 
// (C) RUN DEMO() AFTER 2 SECONDS
setTimeout(demo, 2000);
 
// (D) NOTE - TIMEOUT IS ASYNC, THIS WILL CONTINUE TO RUN!
console.log("Third");
  • (A & C) What is another way to emulate a “delay”? Just set the function in a good old timer – setTimeout(FUNCTION, MS).
  • But please take note extra note that setTimeout() is asynchronous.
    • console.log("First") will run first.
    • setTimeout(demo, 2000) will prime the function to run after 2 seconds.
    • console.log("Third") will run next.
    • demo() and console.log("Second") will run after a 2 seconds delay.

 

METHOD 3) ASYNCHRONOUS WITH TIMEOUT

3-async-timeout.js
// (A) ASYNCHRONOUS FUNCTION
async function demo () {
  // (A1) DO SOMETHING
  console.log("First");
 
  // (A2) WAIT 2 SECONDS
  await new Promise(res => setTimeout(res, 2000));
 
  // (A3) PROCEED
  console.log("Second");
}
 
// (B) GO!
demo();

Lastly, this should be pretty self-explanatory even if you have not touched on asynchronous functions – await new Promise(res => setTimeout(res, 2000)) will wait for 2 seconds before proceeding. I personally prefer this method, as it is non-blocking – demo() will “wait” in parallel while other scripts can continue to load and run.

 

 

A POSSIBLY BETTER WAY

If you are trying to “wait until something loads” or “pause until the process is complete” – Javascript is event-driven and here’s a better solution.

 

JAVASCRIPT EVENTS

4-event.html
<img src="demo.png" id="demo">
<script>
// (A) IMAGE LOADED
document.getElementById("demo").addEventListener("load", () => {
  console.log("Image loaded");
});
 
// (B) PAGE READY/LOADED
window.addEventListener("DOMContentLoaded", () => {
  console.log("Page ready");
});
window.addEventListener("load", () => {
  console.log("Page loaded");
});
</script>

Yes, there’s no need to do all those “funky wait delays”. Javascript is event-driven, we only need to define “do X when Y is fully loaded”.

 

CUSTOM EVENTS

5-event.html
// (A) ASYNC FUNCTION TO DO SOMETHING
// * DISPATCH "FOO" EVENT WHEN COMPLETE
async function demo () {
  for (let i=0; i<=1000; i++) {
    if (i == 1000) { window.dispatchEvent(new Event("foo")); }
  }
}
 
// (B) LISTEN TO CUSTOM "FOO" EVENT
window.addEventListener("foo", () => {
  console.log("Demo function has finished");
});
 
// (C) GO!
demo();

Trying to wait until a function has finished? Dispatch your own custom event… Or just call another function when it ends.

 

 

EXTRAS

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

 

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 *