Monday, January 20, 2025
HomeProgrammingJavascript - Wait 5 Seconds Before Executing Next Line, How Does It...

Javascript – Wait 5 Seconds Before Executing Next Line, How Does It Work?

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 next console.log("5 seconds later") by 5000 milliseconds (5 seconds).
  • console.log("End") runs immediately after “Start” without waiting for the timeout.
See also  Simplest Way to Print a Java Array

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 a Promise that resolves after the specified ms time (in this case, 5000 ms or 5 seconds).
  • The await keyword makes the execution of the run() function pause for 5 seconds before printing “5 seconds later”.
See also  C Functions

Which method to use?

  • setTimeout() is good for handling simple delays or when you need to execute something after a set period.
  • async/await with Promise 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.
See also  How do you declare and initialize a dictionary in TypeScript?

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x