Wednesday, August 14, 2013

Episode.Next and Web Workers

I finished up all the main development tasks for Episode.Next and submitted for Facebook and Dropbox approval.  Both systems approved the app within 24 hours.  I was expecting Facebook to give me a harder time.  Reading through all of their usage guidelines for the "Watch" action, it is really meant for a website like Netflix or Hulu to post the action and provide a link to where you can watch the show.  I am redirect to TheTVDB.  Anyway, it passed.

As I was once taught as an engineer, get it working first, then optimize.  After I got it working there were two major performance issues related to syncing: 1) calling to the Dropbox API to sync everything there and 2) calling to TheTVDB to check for new episodes.  Each of those was taking about thirty seconds.  JavaScript is, by definition, single threaded.  So while those things were doing their thirty second sync, the entire UI was blocked.
I thought I could use Web Workers to solve this problem.  This was the promise of web workers.  Have a long background task you need to execute?  Just use web workers.  The challenge I ran into was that Web Workers exist in their own security context without any access to the document and can only communicate with the main thread by posting Strings back and forth.  I wasn't able to get the Dropbox JavaScript libraries to work inside of the web worker, so I gave up on that approach and went back to the tried and true method.  I made all the syncing operations iterative.  Then I would do one iteration and use setTimeout to surrender control and get it back as soon as the UI thread did some stuff.  I'm still having some problems, so I'm thinking of increasing the log.
I'm still having a great time.