gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
How do I artifically add delay in JS: await setTimeout(() => {}, 2000);
- User
How do I artifically add delay in JS: await setTimeout(() => {}, 2000);
- Assistant
To add an artificial delay in JavaScript using
async/await, you can create a function that returns a promise which resolves after a specified amount of time. Here's a clean way to achieve that:function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function runWithDelay() { console.log('Start delay'); await delay(2000); // 2000 milliseconds = 2 seconds console.log('End delay'); } runWithDelay();In this code:
delayis a function that takes a time duration in milliseconds (ms) and returns a Promise that resolves after that duration usingsetTimeout.runWithDelayis anasyncfunction that callsdelaywithawaitto pause execution for the specified time.- When you run
runWithDelay, it will start immediately, then pause for 2 seconds, and finally print "End delay".
This approach ensures that you can add delays in an async function without blocking the main thread, which is crucial for preserving the responsiveness of your application.