We’ve been iterating on how we deal with infinite loops on CodePen for years. (Round One / Notes, Round Two / Notes).

To be perfectly honest, it’s still not perfect, but we’ve come a long way! For the first time, we’ve compartmentalized it to the point where we’re able to open source it, so here’s that: Infinite Loop Buster on GitHub.

The credit here largely goes to Ariya Hidayat, the creator of Esprima, which is the library used to transform a string of JavaScript into an Abstract Syntax Tree (AST) so that it can be worked with.

The story begins when we started accumulating some bugs in our JavaScript instrumenting. They were largely rooted in ES6 (and +) syntax stuff. As we dug in, it turns out it was rooted in a library called escodegen, which does the job of taking a JavaScript AST and turning it back into a string of JavaScript. It just has some bugs with modern JavaScript syntax. It turns out, as Ariya pointed out to us, we didn’t even really need to be using escodegen! (Here’s a writeup of his on the concept behind this.)

We showed him the code we were currently using to do the infinite loop stopping instrumenting, and he went so far as to rewrite it not only more efficiently and succinctly, but also without the need for escodegen. With only minor tweaks, we were able to put it into production and open source it.

Some other things to know:

  • If you’re looking for a version with no dependencies at all, see loop-protect.
  • If you’re loop is being stopped by us, but you know it’s just a long-running loop, not an infinite loop, you can still adjust the timing.
  • If you find yourself in an infinite loop still, you can force JavaScript not to run at all (so you can fix it) by using an URL param.