We can achieve sleep in JavaScript by using setTimeout. The setTimeout function allows you to execute a function after a specified delay in milliseconds. Here’s an example:
function myFunction() { console.log("Hello after 2 seconds!"); } setTimeout(myFunction, 2000); // This will log "Hello after 2 seconds!" after a 2-second delay.
If you need to handle more complex asynchronous operations, you can use Promises or async/await syntax.
function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function myFunction() { console.log("Start"); await sleep(2000); // This will pause execution for 2 seconds without blocking the program. console.log("End after 2 seconds!"); } myFunction();
async function myFunction() { console.log("Start"); await new Promise(resolve => setTimeout(resolve, 2000)); console.log("End after 2 seconds!"); } myFunction();