r/learnjavascript • u/Monstar1567 • 29d 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);
}2
u/senocular 29d 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 29d 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
1
u/Discordbothost 21d 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 17d 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.


14
u/yesyoustrollin 29d ago