Need private packages and team management tools?Check out npm Teams »

tab-race

1.0.0 • Public • Published

Tab Race

Greenkeeper badge Travis badge standard badge npm

A solution for race conditions between browser threads.

Uses the insert-only IndexedDB add request to ensure that only one thread wins a race.

Goals

  • Robust across browsers
  • Fully tested

Usage

const { race, endRace } = require('tab-race')
 
// will only resolve with true once until the race is ended
// even across sessions, tabs, and workers
if (await race('log-race')) {
  console.log('winner!')
 
  // allow a new winner when this tab is closed
  window.onunload = () => endRace('log-race')
}

API

async race(name)

Resolves with true if this is the single winning execution and false otherwise. Uses indexedDB, so anywhere that can access the same indexedDB databases will participate in the same races (sessions, tabs, and workers for the same domain).

name specifies which race to participate in. Using a different name allows for multiple concurrent races that don't interfere.

endRace(name)

Synchronous function that resets the race with name to allow another winner.

It will successfully end the race when executed in an unload event handler.

Make sure race(name) finishes on all threads before calling endRace(name) or there will be multiple winners. Keep in mind that the minimum setTimeout() length for background tabs is 1000ms.

Install

npm i tab-race

DownloadsWeekly Downloads

1

Version

1.0.0

License

MPL-2.0

Unpacked Size

24.8 kB

Total Files

7

Last publish

Collaborators

  • avatar