Write a function that returns a promise and resolves after a specified delay. Use it to simulate asynchronous operations.
function delay(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); }); }
The delay
the function takes an argument ms
representing the delay time in milliseconds. It creates a new Promise and uses setTimeout
to delay the resolution of the promise by the specified duration. After the delay, the promise is resolved.
You can use this function to simulate asynchronous operations by chaining it with other promises or using it within an async/await context. Here's an example:
console.log('Start');
delay(2000) .then(() => { console.log('Async operation completed!'); })
.catch((error) => { console.error('Error:', error); });
console.log('End');
In the above example, the delay
the function is called with a delay of 2000 milliseconds (2 seconds). The program will print "Start", then after 2 seconds, it will print "Async operation completed!". Finally, it will print "End".
By using the delay
function, you can introduce delays in your code to simulate asynchronous behavior and observe how promises are resolved after the specified delay.