easy-poll

simple poll

Usage no npm install needed!

<script type="module">
  import easyPoll from 'https://cdn.skypack.dev/easy-poll';
</script>

README

api

Overview

Simple polling mechanism. Creating a new instance of the factory will automatically start polling, no need to invoke any sort of init or start method. Callbacks as well as the polling instance properties are settable, providing a powerful and simple way to alter the mechanism of the poll while it is polling. See the spec for more examples.

Installation

$ npm install easy-poll

Usage

//as a browser global
var instance = easyPoll(options);

//common js
var easyPoll = require('easy-poll');
var instance = easyPoll(options);

Parameters

  • options {object} - Hash of options.
    • delay {number} - Interval in ms by which to delay. Defaults to 1000 ms.
    • max {number} - Max number of iterations the each function will run. Defaults to Infinity.
    • each {function} - Callback that runs asynchronously on every iterations, it is supplied with these parameters:
      • current {number} - The current iteration.
      • stop {function} - Callback to manually cease the iteration.
      • next {function} - Must be called in order to proceed to the next iteration.
    • after {function} - Runs after max has been reached or the instance is manually stopped via instance.stop(), it is supplied with these parameters:
      • current {number} - The iteration at which the instance ceased polling.
      • start {function} - If invoked wil restart the polling instance.

Returns

  • {object} - Contains methods to alter the instance.
    • stop {function} - Stops the iteration, accepts an optional callback function that is supplied with two arguments, current and start {function} that restarts the poll.
    • getCurrent {function} - Returns current iteration of instance.
    • setDelay {function} - Set the delay time, accepts a number.
    • setMax {function} - Set the max property, accepts a number.
    • setEach {function} - Set the each callback, accepts a callback function.
    • setAfter {function} - Set the after callback, accepts a callback function.
    • setCurrent {function} - Set the current iteration, accepts a number.

Example

var instance = easyPoll({
  delay: 100,
  max: 10,
  each: function(current, stop, next) {
    //stop it manually
    if (current === 5) {
      stop();
    } else {
    //pass the callback to proceed
      next();
    }
  },
  after: function(current) {
    console.log('done at ' + current);
  }
});

//get the current iteration
instance.getCurr();

//stop the instance externally
instance.stop();

//change the callback
//all instance methods are settable, just supply a callback as the parameter
instance.setEach(function(current, stop, next) {
  next();
})