Join the conversation

Sign in to join this conversation, and others like it, in the communities you care about.


Hey Everybody! Come share Pens, ask front-end coding questions, and get/give feedback with your CodePen pals

CodePen / General

Web Workers and OffscreenCanvas

Web Workers and OffscreenCanvas

CodePen / General · October 10, 2018 at 6:49pm (Edited 3 months ago)
Hi everyone,
This may be of interest to some of you if you are doing CPU-intensive things in JavaScript. As a quick proof of concept, today I moved my robots to a separate background thread.
If your browser both supports the Web Workers API and the OffscreenCanvas interface, Robots are now dancing smoothly in their own separate OS-managed CPU thread.
Workers require a separate JS file, but I wanted all the code be packed in a single html file, all in the JS panel on CodePen. Credits to Roman Liutikov for his nice inliner function trick.
In my example worker code is all contained in the 'theLastExperience' function. Fallback to running from the main thread is achieved with no code duplication.
Thanks to the OffScreenCanvas interface, all canvas painting code can now be handled from the worker code directly. This is really convenient.
I haven’t performed extensive testing. It's working just fine in Chrome (as usual). Tested from my iPhone, Firefox and Edge on W10, Robots running in the main thread.
Feedback is appreciated :-)

October 10, 2018 at 10:58pm

pretty good optimization! I'm definitely going to dig into the code further when i get a chance (and see if i can make a webgl+gpgpu version). A couple of things that jumped out to me as i was reading the code -

* architecture is very solid, i can't suggest any improvements

* like the URL.createObjectURL(new Blob(["(" + fn + ")()"])) approach

* maybe is a confusing variable name, maybe something more descriptive like noWorkers

* pointer at line 446 vs pointer on line 463, they seem to be 2 different things with the same name, which is confusing

* i like that theLastExperience is where all of the worker code is, easy to know where the code i'm looking at will run thanks to the extra level of indentation

  • reply
  • like

October 11, 2018 at 5:14am

Thanks for the pretty detailled code review :)

  • reply
  • like

Another cool side effect I like : Worker threads are secured by design, running in a dedicated global scope. Code can’t be manipulated remotely, i.e. killing requestAnimationFrame and all those things CodePen does.

  • reply
  • like

October 12, 2018 at 11:03pm

October 13, 2018 at 2:02am

wow, i cannot believe this is working at interactive speeds and still cpu-bound

  • reply
  • like

Log in or sign up to chat