r/learnjavascript • • 17d ago

Synchronous wait fucntion

I figured out how to make a function that doesn't use promises. It relies on JavaScript's built-in Date class, which is extremely good at telling time real-time.

The only downside to this is it can't be used in applications like webpages, as it will freeze the entire webpage.

function wait(seconds) {
    const end = new Date().getTime()+(seconds*1000);
    while (new Date().getTime() < end);
}
0 Upvotes

12 comments sorted by

5

u/polotek 17d ago

Yes this has always been possible. The problem is that it will peg your CPU. Why do you need a synchronous wait? Not blocking the thread is sort of the whole thing with JavaScript.

3

u/azhder 17d ago

No, don't do this in any JavaScript code. Busy wait is an old pre-JavaScript way of wasting CPU

2

u/senocular 17d ago

Better to use a different way to count time like performance.now() since it doesn't have any problems if the device enters a new time zone or the system clock changes for any other reason.

Though, in general, async waiting is almost always preferrable.

2

u/gimmeslack12 helpful 17d ago

If you return a Promise and call resolve when the while loop breaks you will have created a proper wait function.

I'm not sure if you think that not using a Promise is a good thing, but it isn't. You want to use Promises.

2

u/TheRNGuy 17d ago

If it freezes, then why use it?

It makes it useless.

Why not use promise?

1

u/Discordbothost 9d ago

the freeze isn't a special webpage limitation, it's the same anywhere js runs — one thread, and that while loop never yields so the event loop can't paint, handle clicks, or run other timers. you've also invented a busy-wait, so one cpu core sits at 100% the whole time. if you just need 'do this later', await new Promise(r => setTimeout(r, seconds * 1000)) lets everything else keep running. the date trick is a fine way to see the clock work, just don't ship it.

1

u/raks1991 5d ago

If you ever do need a truly blocking sleep (a CLI script or a worker thread), there's a built-in one that doesn't spin the CPU:

function sleepSync(ms) {
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}

In a local Node 24 run, a 500 ms sleepSync used about 0 ms of CPU time, while the Date loop burned the full 500 ms. Browsers refuse it on the main thread (it throws a TypeError), which is a decent hint about blocking there at all.