Many programming languages have a sleep perform that can delay a program’s execution for a given variety of seconds. JavaScript lacks this built-in function, however to not fear. On this article, we’ll discover varied strategies to implement delays in your JavaScript code, protecting in thoughts the language’s asynchronous nature.

Desk of Contents

Easy methods to Create a Sleep Perform in JavaScript

For these of you who’re right here for a fast repair and don’t need to dive into the technical particulars, we’ve obtained you lined. Right here’s essentially the most simple manner so as to add a sleep perform to your JavaScript toolbox:

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

console.log('Hiya');
sleep(2000).then(() => { console.log('World!'); });

Run this code, and also you’ll see “Hiya” pop up in your console. Then, after a short two-second pause, “World!” will observe. It’s a neat and efficient method to introduce a delay with out breaking a sweat.

If that is all you got here for, incredible! However for those who’re curious in regards to the “why” and the “how”, there’s extra to study. There are nuances and intricacies in coping with time in JavaScript that you just would possibly discover helpful. So, learn on to search out out extra!

Understanding JavaScript’s Execution Mannequin

Now that we’ve obtained a fast answer beneath our belts, let’s delve into the mechanics of JavaScript’s execution mannequin. Understanding that is essential for successfully managing time and asynchronous operations in your code.

Contemplate the next Ruby code:

require 'web/http'
require 'json'

url = 'https://api.github.com/customers/jameshibbard'
uri = URI(url)
response = JSON.parse(Internet::HTTP.get(uri))
places response['public_repos']
places 'Hiya!'

As one would possibly anticipate, this code makes a request to the GitHub API to fetch my person knowledge. It then parses the response, outputs the variety of public repos attributed to my GitHub account and eventually prints “Hiya!” to the display. Execution goes from high to backside.

Distinction that with the equal JavaScript model:

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

In the event you run this code, it is going to output “Hiya!” to the display, then the variety of public repos attributed to my GitHub account.

It’s because fetching knowledge from an API is an asynchronous operation in JavaScript. The JavaScript interpreter will encounter the fetch command and dispatch the request. It is going to not, nevertheless, await the request to finish. Moderately, it is going to proceed on its manner, output “Hiya!” to the console, after which when the request returns a few hundred milliseconds later, it is going to output the variety of repos.

If any of that is information to you, you must watch this wonderful convention speak: What the heck is the event loop anyway?

Easy methods to Use SetTimeout in JavaScript Correctly

Now that we’ve got a greater understanding of JavaScript’s execution mannequin, let’s take a look at how JavaScript handles delays and asynchronous code.

The usual manner of making a delay in JavaScript is to make use of its setTimeout methodology. For instance:

console.log('Hiya');
setTimeout(() => {  console.log('World!'); }, 2000);

This may log “Hiya” to the console, then after two seconds “World!” And in lots of instances, that is sufficient: do one thing, then, after a brief delay, do one thing else. Sorted!

However sadly issues aren’t at all times that easy.

You would possibly suppose that setTimeout pauses the entire program, however that’s not the case. It’s an asynchronous perform, which suggests the remainder of your code received’t await it to finish.

For instance, say you run this:

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

You’ll see the next output:

Hiya
Goodbye!
World!

Discover how “Goodbye!” seems earlier than “World!”? That’s as a result of setTimeout doesn’t block the remainder of the code from executing.

This implies that you would be able to’t do that:

console.log('Hiya');
setTimeout(1000);
console.log('World');

“Hiya” and “World” will instantly be logged to the console with no noticeable delay occurring in between.

You can also’t do that:

for (let i = 0; i  { console.log(i); }, 1000);
}

Take a second to think about what would possibly occur within the above code snippet.

It received’t print the numbers 0 to 4 with a delay of 1 second between every. ather, the numbers 0 to 4 might be logged to the console concurrently after a delay of 1 second. Why? As a result of the loop doesn’t pause execution. It doesn’t await setTimeout to finish earlier than transferring on to the subsequent iteration.

To acquire the specified output, we have to modify the delay in setTimeout to i * 1000 milliseconds.

for (let i = 0; i  { console.log(i); }, i * 1000);
}

This staggers the execution of the console.log statements, making certain a one-second interval between every output.

The important thing takeaway right here is that setTimeout doesn’t block a program’s execution, quite the JavaScript interpreter will transfer on to course of the remainder of the code and solely come again to execute the callback perform as soon as the timer expires.

So what’s setTimeout really good for? Let’s have a look at that now.

setTimeout() Perform Analyzing and Finest Practices

As you possibly can learn in our setTimeout tutorial, the native JavaScript setTimeout perform calls a perform or executes a code snippet after a specified delay (in milliseconds).

This may be helpful if, for instance, you wished to show a popup after a customer has been looking your web page for a sure period of time, otherwise you need a brief delay earlier than eradicating a hover impact from a component (in case the person by chance moused out).

The setTimeout methodology accepts a reference to a perform as the primary argument.

This may be the title of a perform:

perform greet(){
  alert('Howdy!');
}
setTimeout(greet, 2000);

It may be a variable that refers to a perform (a perform expression):

const greet = perform(){
  alert('Howdy!');
};
setTimeout(greet, 2000);

Or it may be an nameless perform (on this case an arrow function):

setTimeout(() => { alert('Howdy!'); }, 2000);

It’s additionally potential to move setTimeout a string of code for it to execute:

setTimeout('alert('Howdy!');', 2000);

Nevertheless, this methodology isn’t advisable, as:

  • it’s laborious to learn (and thus laborious to take care of and/or debug)
  • it makes use of an implied eval, which is a possible safety danger
  • it’s slower than the options, because it has to invoke the JS interpreter

As talked about, setTimeout is nice for firing a one-off motion after a delay, however it’s additionally potential to make use of setTimeout (or its cousin setInterval) to maintain JavaScript ready till a situation is met. For instance, right here’s the way you would possibly use setTimeout to attend for a sure component to seem on an online web page:

perform pollDOM () {
  const el = doc.querySelector('my-element');

  if (el.size) {
    
  } else {
    setTimeout(pollDOM, 300); 
  }
}

pollDOM();

This assumes the component will flip up sooner or later. In the event you’re unsure that’s the case, you’ll want to have a look at canceling the timer (utilizing clearTimeout or clearInterval).

Rising Timeouts as Various to Sleep Perform in JavaScript

Generally, you would possibly end up desirous to introduce delays in a sequence of operations. Whilst you might use varied strategies to emulate a sleep perform, there’s one other method that’s typically missed: incrementally rising timeouts.

The thought is straightforward: as a substitute of pausing your complete execution thread, you increment the delay for every subsequent operation utilizing setTimeout. This lets you create a sequence of delayed actions with out blocking the browser or compromising the person expertise.

Right here’s a fast instance as an instance:

let delay = 1000; 

for (let i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log(`That is message ${i + 1}`);
  }, delay);

  delay += 1000; 
}

On this instance, the primary message will seem after 1 second, the second after 2 seconds, and so forth, as much as the fifth message after 5 seconds.

Some great benefits of this methodology are that it’s non-blocking, simple to implement, and doesn’t require information of guarantees or async/await. Nevertheless, it isn’t appropriate for complicated asynchronous operations that require exact timing or error dealing with.

Move Management in Trendy JavaScript

It’s typically the case when writing JavaScript that we have to await one thing to occur (for instance, knowledge to be fetched from an API), then do one thing in response (reminiscent of replace the UI to show the info).

The instance above makes use of an nameless callback perform for this objective, but when you want to await a number of issues to occur, the syntax shortly will get fairly gnarly and you find yourself in callback hell.

Fortunately, the language has advanced significantly over the previous few years and now affords us new constructs to keep away from this.

For instance, utilizing async await we are able to rewrite the preliminary code to fetch info from the GitHub API:

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

Now the code executes from high to backside. The JavaScript interpreter waits for the community request to finish and the variety of public repos is logged first, then the “Hiya!” message.

If that is extra the type of factor you’re making an attempt to perform, I encourage you to learn our article Flow Control in Modern JS: Callbacks to Promises to Async/Await.

Bringing Sleep to Native JavaScript

In the event you’re nonetheless with me, then I assume you’re fairly set on blocking that execution thread and making JavaScript wait it out.

Right here’s the way you would possibly try this:

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

console.log('Hiya');
sleep(2000);
console.log('World!');

As anticipated, it will log “Hiya”, pause for 2 seconds, then log “World!”

It really works through the use of the Date.now methodology to get the variety of milliseconds which have elapsed since January 1, 1970 and assigning that worth to a date variable. It then creates an empty currentDate variable, earlier than getting into a do ... whereas loop. Within the loop it repeatedly will get the variety of milliseconds which have elapsed since January 1, 1970 and assigns the worth to the beforehand declared currentDate variable. The loop will maintain going whereas the distinction between date and currentDate is lower than the specified delay in milliseconds.

Job achieved, proper? Effectively, not fairly …

Easy methods to Write Higher Sleep Perform in JavaScript

Possibly this code does precisely what you’re hoping for, however bear in mind that it has a big drawback: the loop will block JavaScript’s execution thread and be sure that no one can work together along with your program till it finishes. In the event you want a big delay, there’s an opportunity that it could even crash issues altogether.

So what to do?

Effectively, it’s additionally potential to mix the strategies discovered earlier within the article to make a much less intrusive sleep methodology:

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

console.log('Hiya');
sleep(2000).then(() => { console.log('World!'); });

This code will log “Hiya”, wait for 2 seconds, then log “World!” Beneath the hood, we’re utilizing the setTimeout methodology to resolve a promise after a given variety of milliseconds.

Discover that we have to use a then callback to ensure the second message is logged with a delay. We will additionally chain extra callback features onto the primary:

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

This works, however it appears ugly. We will fairly it up utilizing async ... await:

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

async perform delayedGreeting() {
  console.log('Hiya');
  await sleep(2000);
  console.log('World!');
  await sleep(2000);
  console.log('Goodbye!');
}

delayedGreeting();

This appears nicer, however it implies that no matter code is utilizing the sleep perform must be marked as async.

After all, each of those strategies nonetheless have the drawback (or function) that they don’t pause your complete program execution. Solely your perform sleeps:

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

async perform delayedGreeting() {
  console.log('Hiya');
  await sleep(2000); 
  console.log('World!');
}

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

The code above logs the next:

Hiya
Goodbye!
World!

Finest Practices for Making a JavaScript Sleep Perform

We’ve explored varied methods to introduce delays in JavaScript. Now let’s recap on which methodology is greatest fitted to completely different situations, and which one you must usually keep away from.

1. Plain setTimeout

console.log('Hiya');
setTimeout(() => { console.log('World!'); }, 2000);
  • 👍 Execs: Easy to grasp, non-blocking.
  • 👎 Cons: Presents restricted management over asynchronous operations.
  • 📝 When to Use: Good for easy, one-off delays, or primary polling.

2. Incremental setTimeout

setTimeout(() => { console.log('Hiya'); }, 1000);
setTimeout(() => { console.log('World!'); }, 2000);
  • 👍 Execs: Non-blocking, simple to implement, and doesn’t require information of guarantees or async/await.
  • 👎 Cons: Not appropriate for complicated async operations. No error dealing with.
  • 📝 When to Use: Helpful for easy sequences with a delay between every step.

3. Blocking the Occasion Loop with a Loop

console.log('Hiya');
const date = Date.now();
let currentDate = null;
do {
  currentDate = Date.now();
} whereas (currentDate - date < 2000);
console.log('World!');
  • 👍 Execs: Mimics conventional sleep habits.
  • 👎 Cons: Blocks your complete thread, can freeze the UI or crash this system.
  • ⚠️ Strongly Discouraged: Solely use this for those who completely have to halt execution and are conscious of the dangers.

4. Utilizing Guarantees with setTimeout

const sleep = perform(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
console.log('Hiya');
sleep(2000).then(() => { console.log('World!'); });
  • 👍 Execs: Non-blocking, extra management over asynchronous operations.
  • 👎 Cons: Requires understanding of guarantees. Longer promise chains can get a bit messy.
  • 📝 When to Use: Whenever you want extra management over timing and asynchronous operations.

5. Utilizing async/await with Guarantees

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

async perform delayedGreeting() {
  console.log('Hiya');
  await sleep(2000);
  console.log('World!');
  await sleep(2000);
  console.log('Goodbye!');
}

delayedGreeting();
  • 👍 Execs: Clear syntax, simple to learn, non-blocking.
  • 👎 Cons: Requires understanding of async/await and guarantees. Requires “wrapping” perform exterior of modules.
  • Strongly Really useful: That is essentially the most trendy and clear method, particularly when coping with a number of asynchronous operations.

Conclusion

Timing points in JavaScript are the reason for many a developer headache, and the way you cope with them relies on what you’re making an attempt to attain.

Though a sleep perform is current in lots of different languages, I’d encourage you to embrace JavaScript’s asynchronous nature and take a look at to not struggle the language. It’s really fairly good whenever you get used to it.

When you’ve got any questions, please head over to the Pylogix forums and begin a dialogue.

FAQs About Sleep, Pause & Wait Features in JavaScript

Listed below are some often requested questions on creating delays in JavaScript.

Is there a sleep in JavaScript?

No, JavaScript doesn’t have a built-in sleep perform, however you possibly can emulate one utilizing setTimeout or guarantees with async/await.

Is it potential to make use of the JavaScript sleep perform in loops?

Sure, you should utilize the sleep perform in loops for those who’re working inside an async perform or a module:
async perform sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms));
}
for (let i = 0; i < 5; i++) { console.log(`Loop rely: ${i}`); await sleep(1000); // Sleep for 1 second
}

Easy methods to sleep for 1 second in JavaScript?

You should utilize setTimeout like this:
setTimeout(() => { console.log('1 second handed'); }, 1000);
Or use async/await with guarantees:
await new Promise(resolve => setTimeout(resolve, 1000)) .then(() => { console.log('1 second handed'); });

How do you sleep 5 seconds in JavaScript?

Much like sleeping for 1 second, simply change the time to 5000 milliseconds:
setTimeout(() => { console.log('5 seconds handed'); }, 5000);
Or use async/await with guarantees:
await new Promise(resolve => setTimeout(resolve, 5000))
.then(() => { console.log('5 seconds handed'); });

Easy methods to make a timeout in JavaScript?

You’ll be able to create a timeout utilizing the setTimeout perform:
setTimeout(() => { /* Your code right here */ }, timeInMilliseconds);

What does wait() do in JavaScript?

There isn’t any native wait() perform in JavaScript. Nevertheless, you possibly can create the same impact utilizing async/await with guarantees or setTimeout.