Web Workers and Infinite Loops

CodePen does some extra fancy dancing to prevent you from executing infinite loops and freezing the browser. If we didn't, you could find yourself in situation with unsaved work and no way to save it. That would suck. So, we try to stop your loops for you if they don't appear to exit in a reasonable amount of time.

We do this by literally altering your JavaScript and injecting lines inside and just after loops. If you peak in there, you might see stuff referencing window.CP.shouldStopExecution. 99.9999% of the time, you'll never notice or care and it will effect nothing.

There is one place it does stir up a little trouble, and that's if you're trying work with Web Workers. Normally, you link up a Web Worker as an external file. That works totally fine, and in fact, you can link to another Pen to do that and it will work fine. The trouble comes up when you try to use a library like Dream Jobs to write Web Workers right within your main JavaScript. When you do that, we still do our JavaScript manipulation inserting our functions, but they will error out because Web Workers don't have a window object.

We might be able to fix this on our side at some point, but it's so rare we're going to avoid that technical debt until we see it being a bigger problem for users.

For now, the fix is to "polyfill" our functions with blank functions so they don't error out in your Web Worker code.

const window = {
  CP: {
    shouldStopExecution: () => false,
    exitedLoop: () => false
  }
};

The post Web Workers and Infinite Loops appeared first on CodePen Blog.