JavaScript Promises with setTimeout Examples
Promise with setTimeout:
Write a JavaScript function that creates a Promise that resolves after a given number of milliseconds.
Solution-1: Using a Named Function
Code:
// Function to create a promise that resolves after a given number of milliseconds
function delay(milliseconds) {
// Return a new promise
return new Promise((resolve) => {
// Use setTimeout to delay execution
setTimeout(() => {
resolve(`Resolved after ${milliseconds} milliseconds`);
}, milliseconds);
});
}
// Test the function
delay(2000).then((message) => console.log(message)); // Logs: Resolved after 2000 milliseconds
Output:
"Resolved after 2000 milliseconds"
Explanation:
- The delay function takes milliseconds as an argument.
- It returns a new Promise.
- Inside the promise, setTimeout delays execution for the specified milliseconds.
- After the delay, the promise resolves with a message indicating the delay duration.
- The .then() method logs the resolved message when the promise resolves.
Solution-2: Using an Arrow Function
Code:
// Arrow function to create a promise that resolves after a given time
const delay = (milliseconds) =>
new Promise((resolve) => {
// Use setTimeout for the delay
setTimeout(() => resolve(`Done waiting ${milliseconds} ms`), milliseconds);
});
// Test the function
delay(3000).then((message) => console.log(message)); // Logs: Done waiting 3000 ms
Output:
"Done waiting 3000 ms"
Explanation:
- The delay function is written as an arrow function.
- It takes milliseconds as input and returns a new Promise.
- Inside the promise, setTimeout is used to wait for the specified time before resolving.
- The message includes the delay time and is logged when the promise resolves.
See the Pen promises-and-async-await-exercise-11 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Wrapping Asynchronous operations in JavaScript Promises.
Next:Efficiently Combine Sync and Async tasks with Promise.all.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics