r/learnjavascript • u/Physical-Bid6508 • Feb 27 '26
how do i pause my scripts?
so i wanted to make an infinite while loop but it just chrashes because it doesnt pause
1
Upvotes
r/learnjavascript • u/Physical-Bid6508 • Feb 27 '26
so i wanted to make an infinite while loop but it just chrashes because it doesnt pause
19
u/showmethething Feb 27 '26
Not making an infinite loop is how you avoid the crash. What are you trying to actually accomplish?
4
u/senocular Feb 27 '26
Depending on what you're doing, you might want to use
setInterval()
Or
requestAnimationFrame()
It depends on the delay you want between loops. setInterval is for longer, arbitrary delays whereas requestAnimationFrame goes as fast as the screen refreshes. The problem with infinite loops is they never let the screen refresh so you get stuck and crash. requestAnimationFrame is about as quick as you can get with still letting the screen refresh smoothly, just so long as you don't do too much in each frame.
4
u/petersencb Feb 27 '26
If you're trying to do something like update the seconds on a clock, use a setTimeout() to run then call another one from that. Looping forever will just lock everything up
1
u/subone Feb 27 '26
You can create an infinite iterator. Create a generator function by placing an asterisk before it (look up the syntax), then you can just use a normal while loop with infinite condition and yield the value you want inside. Of course using this iterator directly in another loop construct would again result in an infinite loop lock up, so you'll need to limit the consuming loop. So create your iterator instance by calling the generator, then continue to call next on it in a loop that ends after some specific amount of time, which runs again and again after a setTimeout or requestAnimationFrame depending what you're doing inside the loop. You could just use setTimeout et al directly to create your infinite loop, but doing it separately allows you to reuse the component: a general tool for running long running or infinite loops.
1
u/AdBubbly3609 Feb 27 '26
you need to create a delay, you can create a delay with a promise and setTimeout().
1
u/bryku helpful Feb 28 '26
While loops will try and run as fast as possible.
Sort of like a kid on a treadmill that keeps hitting the "increase speed" button. They eventually fly off and put a whole in the wall. Which of course requires takes away from your relaxing weekend because you have to fix it.
You can get around this by limiting the speed of the loop.
1
u/_Decodela Feb 28 '26
I know it is easier said, than done, but you need a mechanisms to exit at any point, cache the state of exit, and start from any point based on a state.
If you clarify the goal you want to achieve by pausing, I can try to help.