We do some pretty fancy-dancing around here at CodePen to prevent infinite loops in JavaScript from locking up the browser. Yes, as smart as browsers are, you can still write an infinite loop and completely lock up the browser to the point it’s absolutely frozen and won’t respond at all. We don’t want that to happen in the CodePen editor, as it might even cause lost work (gasp!).

So, we have what we call Infinite Loop Protection which goes so far as to insert little checks into the JavaScript code you author before it is executed that allow us to break out of the loop if we have to. The vast majority of the time, this catches accidental infinite loops and allows you to fix them.

In some rare cases, our detection stops loops that it shouldn’t. This is more of an art than a science. We had to pick some magic timing numbers that just kinda felt right to us.

  • Start monitoring: after 2 seconds
  • Maximum time inside a loop without exiting loop: 2.2 seconds
  • Stop monitoring after: 5 seconds

These manifest as variables that you can change if you need to.

For example, the middle variable up there is the one you’d most likely change.

window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 6000;

Put that at the top of your JavaScript to alter that value before it’s used.

You can actually explore the code for this right in our own console!

Other things to know: