In JavaScript, you can make the execution of the next line wait for 5 seconds using setTimeout()
or by using async/await
with a Promise
. Here’s how to do it using both approaches:
1. Using setTimeout()
setTimeout()
allows you to delay the execution of a function by a specified amount of time (in milliseconds).
Example:
console.log("Start");
// Wait for 5 seconds before executing the next line
setTimeout(function() {
console.log("5 seconds later");
}, 5000);
console.log("End");
Explanation:
- The first
console.log("Start")
prints immediately. setTimeout()
delays the execution of the nextconsole.log("5 seconds later")
by 5000 milliseconds (5 seconds).console.log("End")
runs immediately after “Start” without waiting for the timeout.
2. Using async/await
with Promise
If you want to make the code more readable and wait for a certain period in an asynchronous function, you can use async/await
along with Promise
.
Example:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
console.log("Start");
// Wait for 5 seconds
await delay(5000);
console.log("5 seconds later");
}
run();
Explanation:
- The
delay()
function returns aPromise
that resolves after the specifiedms
time (in this case, 5000 ms or 5 seconds). - The
await
keyword makes the execution of therun()
function pause for 5 seconds before printing “5 seconds later”.
Which method to use?
setTimeout()
is good for handling simple delays or when you need to execute something after a set period.async/await
withPromise
is preferred for more complex scenarios, especially if you’re dealing with asynchronous code and want to write it in a sequential, easy-to-read manner.