Unlike Java or Python, Javascript does not have a built-in sleep function. So, how might you be able to implement a method with the same functionality as the sleep function?
A simple way to create a delay in Javascript is to use the setTimeout
method. The example below would log Hello
, wait two seconds, and then log World
. For many, this might be enough to do the trick.
console.log("Hello");setTimeout(() => { console.log("World!"); }, 2000);
Still, the noticeable drawback is that setTimeout
is an asynchronous method, meaning that the code below will log Hello
, Goodbye!
, and then, World!
. This could be a problem for some of your programs if you want the program to print in the order Hello
, World!
, and Goodbye!
.
console.log("Hello");setTimeout(() => { console.log("World!"); }, 2000);console.log("Goodbye!");
Here’s a better way to create a delay:
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();
The sleep
function above utilizes the setTimeout
function to resolve a Promise
after a specified number of milliseconds.
The asynchronous function allows us to return a Promise
, and we use await
to get the return value. With this, we can utilize the sleep
method in the function to set up a delay.
Some things to know:
The method does not pause the entire program, only the async
function
await
only pauses the current async
function
The ES6 feature Promise
allows us to design this sleep function
Free Resources