Implement a function to create a promise that resolves after a given delay.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
1. The function should return a new Promise.
2. The Promise constructor takes a function with a resolve argument.
3. Use setTimeout within the Promise constructor.
4. After the specified delay, call the resolve() function.
function delay(ms) {
return new Promise(resolve => {
setTimeout(() => {
// You can optionally resolve with a value
resolve(`Resolved after ${ms}ms`);
}, ms);
});
}
// Example usage with async/await
async function testDelay() {
console.log("Starting...");
const result = await delay(2000); // Pauses execution for 2 seconds
console.log(result);
console.log("Finished.");
}
testDelay();