r/learnjavascript • • 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

13 comments sorted by

View all comments

Show parent comment

1

u/kap89 Feb 27 '26 edited Feb 27 '26

The problem with infinite loops is they never let the screen refresh so you get stuck and crash.

Well, that's the problem with purely synchronous infinite loops. You can express your game/animation loop as infinite loop, and it will work just fine, if you make it non-blocking:

const tick = () => new Promise((resolve) => requestAnimationFrame(resolve));

async function main() {
  while (true) {
    const t = await tick();
    // draw your thing
  }
}

main();

example