Heads up! This blog post hasn't been updated in over 2 years. CodePen is an ever changing place, so if this post references features, you're probably better off checking the docs. Get in touch with support if you have further questions.

TL;DR: Infinite loops suck in JavaScript. They lock up the browser. It’s a fairly difficult problem to solve. We didn’t quite get it right the first time. But now, we think we’re a lot closer and you should be protected from them throughout CodePen.

The last time we talked about stopping infinite loops here on the blog, we told you were were stopping them in the grid. That was our first step on this journey. It was important one. It’s completely uncool to be browsing around CodePen only to have your browser lock up without expecting it1. Before we had this feature, it used to happen to me personally all the time since I am constantly rummaging through Recent Pens in search of interesting work.

The stakes were also lower there. If a preview of a Pen in the grid doesn’t run, it’s not the end of the world. The Pen itself still would still work fine in all the actual views.

But we knew that stopping infinite loops inside the Editor (and the other views) was very important as well. There is even a risk of losing work, if you accidentally execute an infinite loop on a Pen with unsaved work2.

So we started porting over our infinite loop stopping code to the Editor. Only, as many of you are sadly aware, we didn’t quite have it dialed in quite right. There were too many false positives – code getting stopped that shouldn’t have been and even (true negatives?) where infinite loops weren’t being stopped.

Yikes, sorry about that!

Our own Alex Vazquez is the man on the job, and he’s been iterating on this problem for a while now. We tried timing how loops ran for. We tried looking for certain types of loops (for instance, not interfering with requestAnimationFrame). We tried measuring the FPS (frames per second) of a rAF loop to test if the Pen was choking. Alex wrote all about the iterations he tried.

Ever the stoic, I carried on.

Ultimately he figured out a clever and simple solution where we simply test to see if a loop ever exits itself. This of course won’t catch any possible infinite loop, but it will catch the vast majority of stupid-mistake infinite loops and not have much of an impact otherwise.

Bonus: it’ll try to catch the line number for you if it can.

1 One way to ensure you’ll for sure never see an infinite loop in the grid is if you turn on image previews instead of iframes.

2 We used to try and prevent this by not executing JavaScript until you moved your cursor away from the line you were editing, but that’s unnecessary now so we’ve removed it.