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.