The sleep()
function is present in PHP, C, Java, and GO, and it is used to pause the execution of code for a particular amount of time. JavaScript has no dedicated sleep()
function. Still, JavaScript is a flexible language, offering a few alternatives.
setTimeout() method
Unlike our other tutorials, this guide won't show the outputs in the console. Instead, you have to open a compiler on your own and see how the alternatives to sleep()
behave in their natural environment. Let's start with a basic way to emulate sleep in JavaScript by using a setTimeout
method. The method looks like this:
console.log('Java');
setTimeout(() => {
console.log('Script');
}, 5000);
// Output:
// Java
// * 5 seconds *
// Script
We first log the word "Java", use a setTimeout
command to specify a 5-second timeout, and then attempt to log "Script". This behavior will be replicated with no issues when run through a compiler. However, it's not that easy to replace one method with another and expect no downsides. Try the following code example:
console.log('Learning');
setTimeout(() => {
console.log('Java');
}, 5000);
console.log('Script');
// Output:
// Learning
// Script
// * 5 seconds *
// Java
When you create a delay this way, the commands work asynchronously. Thus, the output you get will first input Learning
and Script
, then include Java
in a 5-second timeout. That's why this approach might not be the most suitable for putting a specific log into sleep.
delayedGreeting method
If you'd like to omit an asynchronous output, it could be a great way to use the async await
approach. That's why you should include the async
and delayedGreeting
parameters to separate these three words by a 5-second interval. If you follow this logic, the code sample looks like this:
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function delayedGreeting() {
console.log('Learning');
await sleep(5000);
console.log('Java');
await sleep(5000);
console.log('Script');
}
delayedGreeting();
// Output:
// Learning
// * 5 seconds *
// Java
// * 5 seconds *
// Script
When you try running this code through a compiler, you'll see that words "Learning", "Java", and "Script" will be logged with a 5-second interval. However, when you use a pseudo sleep
option, you should permanently mark async
to work correctly.
Also, this approach includes await
to get to the return value after a specified time interval. Whether you're using the first approach or the second one, you won't stop the entire program from running. You can only pause a particular function, which might not be something you would like to do.
Date.getTime() method
While the first example is an asynchronous one, there is a way to use the synchronous version. This method is strongly discouraged because it can bring dozens of code mistakes, such an opportunity is always possible. Take a look:
const sleepSync = (ms) => {
const end = new Date().getTime() + ms;
while (new Date().getTime() < end) {
/* do nothing */
}
};
const printNumbers = () => {
console.log('Learning');
sleepSync(5000);
console.log('Java');
console.log('Script');
};
printNumbers();
// Output:
// Learning
// * 5 seconds *
// Java
// Script
As you can see, we use the sleepSync
and Date.getTime
methods to specify the initial parameters in the first place. Then, we include the console logging, alongside mentioning that sleepSync has a 5-second interval. The synchronous logging will happen, but please note that such a perspective can also conflict with other code lines within your program.
Synchronous execution of such code blocks the main thread(flow) of execution, which can cause freezes in other processes (for example - UI)
Async and loop
In one of the previous examples we were obliged to use the async method to keep the sleep running as expected. There is always a way to apply the same features using a loop. If you want to experiment with this method on your own, run the following code sample:
const list = [5, 6, 7, 8];
const doSomething = async () => {
for (const item of list) {
await sleep(5000); // asynchronous version
console.log(`${item} => 🍔`);
}
};
doSomething();
// Output:
// * 5 seconds *
// 5 => 🍔
// * 5 seconds *
// 6 => 🍔
// * 5 seconds *
// 7 => 🍔
// * 5 seconds *
// 8 => 🍔
In this case, we include the list: 5
, 6
, 7
, 8
, alongside specifying a 5-second interval, followed by logging a hamburger emoji after that. While this code might seem complex, it works like a loop, allowing you to get the output repeatedly.
Sleep: JavaScript concerns
If you've tried all code samples on your own, you've probably realized already that working around sleep
in JavaScript is still complicated. Using a basic setTimeout()
approach makes it possible to run the asynchronous command. Alternatively, there is a way of using the async await
approach or synchronous getTime
method.
Regardless of what approach you use, after all, it's still impossible to fully replicate the sleep
functionality as it is present in other programming languages. That's why you should think twice before using any of the mentioned methods.
Test yourself
Task 1. Use a simple
setTimeout
method to log the words 'Java' and 'Script' with a 7-second interval.
Solution:
console.log("Java");
setTimeout(() => { console.log("Script"); }, 7000);
Task 2. Try experimenting with a
delayedGreeting
method to separate the words: 'We', 'are', 'learning', and 'JavaScript' with a 2-second interval:
Solution:
function sleep(ms) {
return new Promise(
resolve => setTimeout(resolve, ms)
);
}
async function delayedGreeting() {
console.log("We");
await sleep(2000);
console.log("are");
await sleep(2000);
console.log("learning");
await sleep(2000);
console.log("JavaScript");
}
delayedGreeting();
Task 3. Use a
getTime
synchronous method to log the exact words 'We', 'are', 'learning', and 'JavaScript' with a 2-second interval after logging the word 'We'.
Solution:
const sleepSync = (ms) => {
const end = new Date().getTime() + ms;
while (new Date().getTime() < end) { /* do nothing */ }
}
const printNums = () => {
console.log("We");
sleepSync(2000);
console.log("are");
console.log("learning");
console.log("JavaScript");
};
printNums();