Alex Bosworth's Weblog

developing software, living the expat life in beijing, other fun stuff!

previous projects: alchemy, swik, open source stuff, now adylitica.

Working with Javascript Worker Threads

When the Web Workers feature was announced for the good browsers (safari/chrome/firefox), it seemed to me like something fairly cool but mostly useless. How often do you really need to calculate a Fibonacci sequence in the browser, as Mozilla suggests?

Well I finally found a legit use for it in TweetBe.at, in calculating follow back percentages - which is a major new feature for the site.

Currently other Twitter apps show you a twitter users’ follow back percentage by comparing the total follower total to the total following total. But that ignores the fact that followers and followings may be completely different sets.

Enter Worker Threads. To calculate the intersection between hundreds of thousands of followers and following in id matrices, even Chrome on my Macbook Pro was having a tough time and stalling the UI. 

The Documentation for Web Workers is terrible, but it’s actually a straightforward feature, although unfortunately you must have a separate javascript file for your workers, something I feel is a mistake.

To show you how easy it is here is my main JS file code:

var intersections = new Worker('intersections.js');
  intersections.onmessage = function(event) {
  showIntersections(event.data);
};

OK and now the worker code

self.onmessage = function(event) {
  var results = findIntersections(event.data);
  return postMessage(results);
}

Easy as pie, and very useful in a pinch.

Comments (View)
blog comments powered by Disqus