Synchronous delay in code execution

Variation on the accepted answer which is just as good as this one.

Also, I agree with the caveats of preferring setTimeout and asynchronous function calling but sometimes e.g., when building tests, you just need a synchronous wait command…

function wait(ms) {
    var start = Date.now(),
        now = start;
    while (now - start < ms) {
      now = Date.now();
    }
}

if you want it in seconds, divide start ms by 1000 on the while check…

=== EDIT ===

I noticed that my answer has bubbled to the top but it really shouldn’t be the top answer. That was written as an alternative in case you cannot use async / await in your code or you’re waiting for a trivial amount of time (like a second or two for testing).

The top answer should note that the async/await pattern is a much better way of doing this and will significantly use less energy and CPU cycles.

See @michaelolof ‘s answer below for example….

const wait = (msec) => new Promise((resolve, _) => {
  setTimeout(resolve, msec));
});

(async () => {
  console.log("Start...")
  await wait(5000);
  console.log("...End")
})();

Leave a Comment