How to pause execution for 5 seconds in JavaScript

2 Answers

0 votes
function pause(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}

async function run() {
  console.log("Pausing for 5 seconds...");
  await pause(5000);
  console.log("Resuming execution.");
}

run();


/*
run:

Pausing for 5 seconds...
Resuming execution.

*/




 



answered Apr 30, 2025 by avibootz
0 votes
console.log("Pausing for 5 seconds...");

const pause = (milliseconds) => {
  const start = Date.now();
  while (Date.now() - start < milliseconds) {
    // wait loop
  }
};

pause(5000);

console.log("Resuming execution.");



/*
run:

Pausing for 5 seconds...
Resuming execution.

*/

 



answered Apr 30, 2025 by avibootz

Related questions

1 answer 149 views
2 answers 169 views
1 answer 142 views
1 answer 163 views
1 answer 119 views
119 views asked Apr 30, 2025 by avibootz
1 answer 140 views
2 answers 144 views
...