Go to file
2024-03-20 15:05:23 +00:00
index.js remove last vestiges of old array rebuild 2024-03-20 15:05:23 +00:00
LICENSE Initial Commit 2024-03-20 11:57:46 +00:00
package.json remove last vestiges of old array rebuild 2024-03-20 15:05:23 +00:00
README.md Initial Commit 2024-03-20 11:57:46 +00:00

SimplePollManager

This is a simple class that operates as a singleton to handle objects that want to be polled.

So, you have some class that needs to be polled occasionally, and there may be more than one. So you write your traditional polling method to handle this and hook it to a setInterval

constructor(interval = 1000) {
  this.interval = interval;

  // see https://developer.mozilla.org/en-US/docs/Web/API/setInterval#the_this_problem
  this.poll = this._poll.bind(this);

  this.expiry = new Date( Date().now + 86400 );

  this.intervalID = window.setInterval( this.poll, this.interval );
}

_poll() {
  if ( this.expiry < Date().now ) {
    this.shutdown();
  }
}

But the number of timers available is limited and there could be lots of objects to handle. So, enter SimplePollManager.

We'll need to adjust the objects we're going to poll, but nothing drastic. Drop the interval creation and ensure we return a truthy value from the poll.

constructor(interval = 1000) {
  this.interval = interval;

  // see https://developer.mozilla.org/en-US/docs/Web/API/setInterval#the_this_problem
  this.poll = this._poll.bind(this);

  this.expiry = new Date( Date().now + 86400 );
}

_poll() {
  if ( this.expiry < Date().now ) {
    this.shutdown();
  }
  return this.interval;
}

Then create yourself a SimplePollManager instance with an interval that covers the resolution needs and attach the object

const myPoller = new SimplePollManager( 500 );

myPoller.addPoller( myObj.poll );

myPoller.startPoller();

The poll function should return a truthy value to indicate it still wants to be polled. This value can be one of three types;

  • true
  • A number of milliseconds indicating an interval (next poll will be Date.now() + value )
  • A Date object

So, if our object expiry is a constant the above snippets could be refined to

constructor(interval = 1000) {
  this.interval = interval;

  // see https://developer.mozilla.org/en-US/docs/Web/API/setInterval#the_this_problem
  this.poll = this._poll.bind(this);
}

_poll() {
  this.shutdown();
  return false;
}

and

const myPoller = new SimplePollManager( 500 );

myPoller.addPoller( myObj.poll, undefined, myObj.expiry );

myPoller.startPoller();