Web Worker Counter

An example of using breathe.js within a Web Worker. Web Workers are individually single-threaded, so if left in a long-looping function, they normally can't respond to messages. But with breathe.js, a Web Worker can easily automatically exit a function and respond to messages and then return to that function to continue working.

counter-worker.js:

importScripts('../breathe.js');

// Because web workers don't need to respond as much as a web page, you can set 
// batch time to be higher to be more efficient. A higher amount means that the 
// web worker will likely take longer to respond to messages (breathe will block
// for that amount of time).

breathe.setBatchTime(100); // experimental feature

var i = 0;

self.addEventListener('message', function (e) {
  self.postMessage(i);
});

var synchronousLoop = function () {
  while (true) {
    i++;
  } 
};

var asynchronousLoop = function () {
  breathe.loop(function () { return true; }, function () {
    i++;
  });
};

asynchronousLoop();
// synchronousLoop();

Source: