Write nonblocking JavaScript with breathe.js

How does it work?

breathe.js offers a replacement to traditional loops, function calls, and code blocks that automatically exit a function after a certain amount of time and allow the webpage to respond, before returning to the function.

As a simple example, in traditional JavaScript, you may have a long looping function:

function longLoopingFunction() {
  var i;
  for(i = 0; i < 100000; i++) {

Here trickyFunction() runs 100,000 times, without letting any other code run or UI respond. But with breathe.js, the same code can be written as:

function breathableLongLoopingFunction() {
  return breathe.times(100000, function (i) {

Here the function also runs sequentially, but if it runs for too long (over 17 milliseconds by default), breathe.js relinquishes the main thread to allow other functions to run or UI to respond, then runs the remaining loop, repeatedly relinquishing if necessary.

By using promise conventions and nested functions, converting code is usually straightforward, preserving a function's overall structure and logic. Converting code makes it asynchronous, and adds methods to stop, pause, and unpause the code. Read more about how to use it on the 'Using breathe.js' page.

Can't Web Workers run nonblocking code?

Web workers are designed to run asynchronous, nonblocking code (in another thread, to boot!), but unfortunately they can't do everything. Variables aren't easily shared with a page's main thread, instead relying on message passing. Workers can't acccess DOM, nor can most access a canvas (though there is an OffscreenCanvas in development). Since breathe.js can run inside the main thread of a page, it can access its variables, DOM, and canvases.

Web workers still use a single thread within the worker, so a computation-heavy function can block other code— namely message handling— from running. Breathe.js works within web workers, so they can respond in the middle of executing a long-running function. It also makes it easy to pause and unpause code running within the worker.

Some notes of warning

How do I get started?

Check out the 'Examples' page to see what you can do with it, and read the 'Using breathe.js' page for an in-depth explanation. Download the source here or on the GitHub project page.