Delay, Sleep, Pause, & Wait in JavaScript

Delay, Sleep, Pause, & Wait in JavaScript

Delay, Sleep, Pause, & Wait in JavaScript. Many programming languages have a sleep function that will delay a program's execution for a given number of seconds. This functionality is absent from JavaScript, however, owing to its asynchronous nature

Many programming languages have a sleep function that will delay a program’s execution for a given number of seconds. This functionality is absent from JavaScript, however, owing to its asynchronous nature. In this article, we’ll look briefly at why this might be, then how we can implement a sleep function ourselves.

We’ve rewritten this popular guide from scratch to provide the best and most up-to-date advice. This article was updated in November 2019.

Understanding JavaScript’s Execution Model

Before we get going, it’s important to make sure we understand JavaScript’s execution model correctly.

Consider the following Ruby code:

require 'net/http'
require 'json'

url = 'https://api.github.com/users/jameshibbard'
uri = URI(url)
response = JSON.parse(Net::HTTP.get(uri))
puts response['public_repos']
puts "Hello!"

As one might expect, this code makes a request to the GitHub API to fetch my user data. It then parses the response, outputs the number of public repos attributed to my GitHub account and finally prints “Hello!” to the screen. Execution goes from top to bottom.

Contrast that with the equivalent JavaScript version:

fetch('https://api.github.com/users/jameshibbard')
  .then(res => res.json())
  .then(json => console.log(json.public_repos));
console.log("Hello!");

If you run this code, it will output “Hello!” to the screen, then the number of public repos attributed to my GitHub account.

This is because fetching data from an API is an asynchronous operation in JavaScript. The JavaScript interpreter will encounter the fetch command and dispatch the request. It will not, however, wait for the request to complete. Rather, it will continue on its way, output “Hello!” to the console, then when the request returns a couple of hundred milliseconds later, it will output the number of repos.

If any of this is news to you, you should watch this excellent conference talk: What the heck is the event loop anyway?.

You Might Not Actually Need a Sleep Function

Now that we have a better understanding of JavaScript’s execution model, let’s have a look at how JavaScript handles delays and asynchronous operations.

Create a Simple Delay Using setTimeout

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example:

console.log("Hello");
setTimeout(() => {  console.log("World!"); }, 2000);

This would log “Hello” to the console, then after two seconds “World!” And in many cases, this is enough: do something, wait, then do something else. Sorted!

However, please be aware that setTimeout is an asynchronous method. Try altering the previous code like so:

console.log("Hello");
setTimeout(() => { console.log("World!"); }, 2000);
console.log("Goodbye!");

It will log:

Hello
Goodbye!
World!

Waiting for Things with setTimeout

It’s also possible to use setTimeout (or its cousin setInterval) to keep JavaScript waiting until a condition is met. For example, here’s how you might use setTimeout to wait for a certain element to appear on a web page:

function pollDOM () {
  const el = document.querySelector('my-element');

  if (el.length) {
    // Do something with el
  } else {
    setTimeout(pollDOM, 300); // try again in 300 milliseconds
  }
}

pollDOM();

This assumes the element will turn up at some point. If you’re not sure that’s the case, you’ll need to look at canceling the timer (using clearTimeout or clearInterval).

If you’d like to find out more about JavaScript’s setTimeout method, please consult our tutorial which has plenty of examples to get you going.

Flow Control in Modern JavaScript

It’s often the case when writing JavaScript that we need to wait for something to happen (for example, data to be fetched from an API), then do something in response (such as update the UI to display the data).

The example above uses an anonymous callback function for this purpose, but if you need to wait for multiple things to happen, the syntax quickly gets pretty gnarly and you end up in callback hell.

Luckily, the language has evolved considerably over the past few years and now offers us new constructs to avoid this.

For example, using async await we can rewrite the initial code to fetch information from the GitHub API:

(async () => {
  const res = await fetch(`https://api.github.com/users/jameshibbard`);
  const json = await res.json();
  console.log(json.public_repos);
  console.log("Hello!");
})();

Now the code executes from top to bottom. The JavaScript interpreter waits for the network request to complete and the number of public repos is logged first, then the “Hello!” message.

If this is more the sort of thing you’re trying to accomplish, I encourage you to read our article Flow Control in Modern JS: Callbacks to Promises to Async/Await.

Bringing Sleep to Native JavaScript

If you’re still with me, then I guess you’re pretty set on blocking that execution thread and making JavaScript wait it out.

Here’s how you might do that:

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

console.log("Hello");
sleep(2000);
console.log("World!");

As expected, this will log “Hello”, pause for two seconds, then log “World!”

It works by using the Date.now method to get the number of milliseconds that have elapsed since January 1, 1970 and assigning that value to a date variable. It then creates an empty currentDate variable, before entering a do ... while loop. In the loop it repeatedly gets the number of milliseconds which have elapsed since January 1, 1970 and assigns the value to the previously declared currentDate variable. The loop will keep going while the difference between date and currentDate is less than the desired delay in milliseconds.

Job done, right? Well not quite …

A Better Sleep Function

Maybe this code does exactly what you’re hoping for, but be aware, it has a large disadvantage: the loop will block JavaScript’s execution thread and ensure that nobody can interact with your program until it finishes. If you need a large delay, there’s a chance that it may even crash things altogether.

So what to do?

Well, it’s also possible to combine the techniques learned earlier in the article to make a less intrusive sleep function:

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

console.log("Hello");
sleep(2000).then(() => { console.log("World!"); });

This code will log “Hello”, wait for two seconds, then log “World!” Under the hood we’re using the setTimeout method to resolve a Promise after a given number of milliseconds.

Notice that we need to use a then callback to make sure the second message is logged with a delay. We can also chain more callbacks onto the first:

console.log("Hello");
sleep(2000)
  .then(() => { console.log("World!"); })
  .then(() => {
    sleep(2000)
      .then(() => { console.log("Goodbye!"); })
    });

This works, but looks ugly. We can pretty it up using async ... await:

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

async function delayedGreeting() {
  console.log("Hello");
  await sleep(2000);
  console.log("World!");
  await sleep(2000);
  console.log("Goodbye!");
}

delayedGreeting();

This looks nicer, but means that whatever code is using the sleep function needs to be marked as async.

Click here.

Of course, both of these methods still have the disadvantage (or feature) that they do not pause the entire program execution. Only your function sleeps:

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

async function delayedGreeting() {
  console.log("Hello");
  await sleep(2000);
  console.log("World!");
}

delayedGreeting();
console.log("Goodbye!");

The code above logs the following:

Hello
Goodbye!
World!

Conclusion

Timing issues in JavaScript are the cause of many a developer headache, and how you deal with them depends on what you’re trying to achieve.

Although a sleep function is present in many other languages, I’d encourage you to embrace JavaScript’s asynchronous nature and try not to fight the language. It’s actually quite nice when you get used to it.

Programming a Javascript Simon Game Tutorial

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

For those who don't know, I'm a full stack web developer who has been in the industry for over 5 years now. There is a lot of things I have learned along the way and I'd like to share that knowledge with anyone wanting to learn!

like this video if you found it useful and would like to see more videos of the same content.

subscribe to my channel if you are trying to improve your abilities as a web developer, software engineer, or even if you are just learning to code.

Don't forget to turn on those bell notifications!

Understanding Memoization And Dynamic Programming in Javascript

Understanding Memoization And Dynamic Programming in Javascript

In this Javascript tutorial I will explain what memoization is, how to use it, when you should use memoization, how to use memoization, what dynamic programming is, how to use memoization in dynamic programming. Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it.

Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it. Memoization is just the act of caching values so that they can be calculated quicker in the future. Memoization is really useful in all parts of programming, but where it is most useful is in dynamic programming. In this video I will explain what memoization is, how to use it, and why it is so useful especially in dynamic programming.

🧠 Concepts Covered:

  • What memoization is
  • When you should use memoization
  • How to use memoization
  • What dynamic programming is
  • How to use memoization in dynamic programming

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript is the programming language of HTML and the Web. JavaScript is easy to learn. This tutorial will teach you JavaScript from basic to advanced. JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Watch this JavaScript tutorial for beginners to learn JavaScript programming from scratch. 👍

⭐️Course Contents⭐️

01 | Introduction

Get an introduction from Bob, as he kicks off the course, sets expectations, and gives you a little guidance for the road ahead.

02 | Setting Up the Development Environment

See how to install Node and Visual Studio Code, and learn why you need each. Watch as Bob writes a first tiny line of code to make sure that the installation is ready.

03 | Basic JavaScript Syntax

Hear about the basics of the JavaScript syntax, including how JavaScript is executed, how to create a properly formed statement, and more.

04 | Variables

Learn what variables are and how to declare, initialize, set, and get values from them.

05 | Data Types

JavaScript works with data types differently than other programming languages do. Learn from Bob as he explains some of the most basic data types and how to determine the type held by a variable.

06 | Type Coercion and Conversion

Sometimes you need to explicitly convert the data type of a value into a different data type. Sometimes JavaScript will do this automatically for you. Bob explains how and why this happens.

07 | Expressions and Operators

Learn how to spot a well-formed expression and how to compose expressions through the combination of operators and operands.

08 | Arrays

Watch as Bob demonstrates how to use arrays, how to add/remove elements of an array, how to access elements of an array using the index, how to get the number of elements in an array, and more.

09 | Function Declaration

Get an introduction to functions, as Bob shows you one way to define a function, how to call the function, how to pass parameters into a function, how to return values from a function, and more.

10 | Function Expressions

Sometimes a function declaration is more than you need. Get details in this lesson, as Bob demonstrates how to use a function expression and how to create an immediately invoked function expression.

11 | Decision Statements

Learn how to add logic to your applications by testing conditions using if / else statements, switch / case statements, and the ternary operator.

12 | Iteration Statements

Watch as Bob introduces the For and While statements, which enable you to loop through lists of values and perform operations on them.

13 | Basics of Scope

Hear an explanation of the notion of the lifetime of variables and their reach into other code blocks, in this discussion of scope.

14 | Returning Functions from Functions

As a building block toward a more sophisticated approach to building JavaScript applications, see how you can return functions from functions.

15 | Object Literals

Objects contain properties and functions that describe attributes of the object and its behavior, respectively. Watch as Bob demonstrates how to create object literals.

16 | Module Pattern and Revealing Module Pattern

Learn how to introduce variables and functions without leaving an unnecessarily large footprint on the global scope.

17 | Closures

Closures allow developers to bind functions to their execution context, including variables, so you can build specialized versions of functions. Learn how closures work and how to create them.

18 | this Keyword

Get the details on the "this" keyword, which causes a lot of confusion for JavaScript developers. Listen as Bob explains what this mysterious object is and how to bend it to your will.

19 | Destructuring

See how to use destructuring, a new feature in JavaScript that allows you to unpack array elements or object properties in a concise syntax.

20 | String Template Literals

Learn about the new string template literal syntax to enable string interpolation, multi-line string formatting, and more.

21 | Regular Expressions

Working with string data, Bob explains how use regular expressions to determine such things as whether a string matches a specific pattern or whether an instance of the pattern exists in a string.

22 | Built-In Natives

Join Bob as he examines native, built-in JavaScript functions that return objects that box the primitive types in order to provide additional helper methods on your values.

23 | Constructor Function Calls with the new Keyword

Learn how constructor functions work, see how to make key distinctions in what they are, and find out why they’re helpful.

24 | Objects and the Prototype Chain

Moving past the absolute beginner matter, listen in as Bob explains how objects work in JavaScript and how you can create an object that is linked to another object.

25 | JavaScript Classes

Bob demonstrates how “syntactic sugar” works on top of the existing functions and prototype chaining to help JavaScript resemble more traditional object-oriented programming languages.

26 | Arrow Functions

The latest version of JavaScript added arrow functions, a shorthand syntax for creating functions. Watch as Bob demonstrates how to create them and shows where they’re useful.

27 | Truthy and Falsy Values

Listen is as Bob circles back to topics that are important (but didn’t easily fit into earlier topics) and looks at the odd way in which JavaScript evaluates certain expressions as truthy and falsy.

28 | null Type

Similar to the undefined primitive type, the null type represents a variable that has no reference to an object when one was expected. Hear an explanation of how and why we should think about nulls.

29 | Date Objects

No discussion of JavaScript would be complete without understanding the Date built-in native function which provides properties and methods for working with dates and times.

30 | String Methods

The built-in native String function provides several very useful methods for manipulating and evaluating strings. Watch Bob demonstrate how to use a few of the most useful ones.

31 | Array Methods

We’ve worked with arrays throughout this course. Now Bob takes a few minutes to show you some of the most useful methods provided by the Array built-in native function.

32 | Error Handling with Try Catch

See how to wrap a try/catch/finally statement around potentially problematic code to anticipate everything that could go wrong with it, and learn other error-handling tips.

33 | Understanding the Document Object Model

Watch Bob examine the web browser environment and how it creates an object graph of nodes that represent elements, their attributes, and text, plus how to properly attach your code to an HTML page.

34 | Working with DOM Nodes

Continuing from the previous video, Bob demonstrates a slightly more compelling example that helps us understand how to manipulate, create, and delete element nodes and attribute nodes.

35 | Course Conclusion

In this final video, Bob briefly adds some closing comments and well wishes. You can also optionally complete a survey to provide insight into how Microsoft can improve this course.

Thanks for watching

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter