Engineer bro!

Wed Dec 15 2021 (2 years ago)

Engineer by mistake!

I am a software engineer by passion

Simulate delay of specified seconds in JavaScript

As a use case, suppose you are building an API that might take 5 sec to respond. In order to simulate this, you need a function that can run for an exact 5 sec.

function delay(sec) {
  let now = Date.now();
  // run while loop for - sec
  while (now + sec * 1000 > Date.now());
}

console.time("delay");
delay(5);
console.timeEnd("delay");

// output - delay: 5.000s

Thank You ❤️

NodeJsJavaScript

© 2021 dsabyte. All rights reserved