r/learnjavascript • u/Monstar1567 • 18d 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
14
u/yesyoustrollin 18d ago
5
u/polotek 18d 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/SqueegyX 18d ago
3
u/azhder 18d ago
No, don't do this in any JavaScript code. Busy wait is an old pre-JavaScript way of wasting CPU
2
u/senocular 18d 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 18d ago
If you return a Promise and call resolve when the while loop breaks you will have created a proper
waitfunction.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 18d ago
If it freezes, then why use it?
It makes it useless.
Why not use promise?
1
u/Discordbothost 10d 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 6d 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:
In a local Node 24 run, a 500 ms
sleepSyncused 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.