JavaScript: How to Sleep/Wait/Delay Code Execution

Introduction

Delaying code execution/simulating a delay has various uses - pausing in a loop for displaying data, waiting for other threads in a multithreaded environment to finish (though, this doesn't replace proper asynchronous programming) or simply lessening loads on a server or client, with successive requests.

Note: Delaying Code Execution is colloquially known as "sleeping" or less commonly as "waiting".

In this short guide, we’ll learn how to wait in JavaScript - or rather, how to sleep/delay code execution, using the setTimeout() function.

The setTimeout() Function

In vanilla JavaScript - we can use the built-in setTimeout() function to "sleep"/delay code execution:

setTimeout(function (){
  // Code to run here
}, delay)

The setTimeout() function accepts two parameters: a function (the code to execute when the delay expires), and the delay (in milliseconds). It will then return a unique positive integer value known as the timeout ID, which identifies the created timeout.

You can call an anonymous function or name it before passing it in:

function printMessage() {
  console.log("I come from a named function!");
}

const timeout1 = setTimeout(() => {console.log("I come from an anonymous function!")}, 1000);
const timeout2 = setTimeout(printMessage, 2000);

console.log('Timeout IDs:', timeout1, timeout2)

This results in:

Timeout IDs:45
I come from an anonymous function!
I come from a named function!

Note: setTimeout() is an asynchronous function - the current timeout will not pause the execution of the next code block.

So that if we have a couple of timeouts, where each timeout calls a function:

setTimeout(() => {console.log("... is 42")}, 4000);
setTimeout(() => {console.log("the universe, and everything")}, 3000);
setTimeout(() => {console.log("The meaning of life")}, 1000);

The output would be:

The meaning of life
the universe, and everything
... is 42

Again, the calls are asynchronous - they don't block each other. The messages are relayed in backward order because the first timeout is longer tan the other two and the second is longer than the third.

For the sake of calling the method sleep() - you can create a simple wrapper that just delegates arguments to the setTimeout() function:

function sleep(functionToExecute, delay){
  let timeoutId = setTimeout(functionToExecute(), delay);
  return timeoutId;
}
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Which you can use instead:

const sayHello = () => {
  console.log('Hello, world!');
}

sleep(sayHello, 1000);

Our sleep() function is just syntactic sugar - it doesn't really add anything. On the other hand, it is more in-line with other languages, most of which have a dedicated sleep() function by that name.

The clearTimeout() Function

The clearTimeout() function is used to cancel a timeout that was previously created with setTimeout(), using the ID returned by the timeout:

let myTimeoutId = setTimeout(() => {
   // do something 
})

Using the returned myTimeoutId, we can cancel the timeout from running:

clearTimeout(myTimeoutId);

Conclusion

In this short guide, we covered how to create a delay in JavaScript, how to use the setTimeout() function, and also how to cancel scheduled code execution.

Last Updated: January 31st, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms