vue-fetch-data icon indicating copy to clipboard operation
vue-fetch-data copied to clipboard

Poll cancel, pause, restart

Open fungl164 opened this issue 7 years ago • 1 comments

Hi,

Thanks for this great plugin.

Was wondering if it would be possible enhance the polling by returning functions to cancel, pause and restart the polling by hooking to the internal setInterval() { ... } function call.

Perhaps the poll option can be expanded to an object like:

{ 
  "interval": 1000,
  "poller": function(cancel, pause, restart, setInterval) { 
     this.cancelPoll = cancel;  
     this.pausePoll = pause;
     this.restartPoll = restart;
     this.setInterval(500);
     ...
  }
}

and then somewhere in your code have

this.cancelPoll();
this.pausePoll();
this.restartPoll();
etc...

Many thanks!

fungl164 avatar Jan 20 '18 16:01 fungl164

Not tested but maybe this might work...

if (poll) {
  // original handling
  if (typeof poll === 'number') {
    setInterval(() => this.$fetch(key), poll)
  }

  // additional handling in case poll is an object with options
  if (typeof poll === 'object' && Object.getPrototypeOf(poll) == Object.prototype) {
    // do nothing if interval value is not a number (could check if > 0)
    if (typeof poll.interval !== 'number') return

    let {interval, poller} = poll
  
    if (poller && typeof poller === 'function') {
      let worker = { runner: null, interval: interval }
      worker.cancel = () => { if (worker.runner) clearInterval(worker.runner) }
      worker.restart = (newInterval = worker.interval) => { 
        worker.cancel()
        worker.interval = newInterval
        worker.runner = setInterval(() => this.$fetch(key), newInterval) 
      }

      worker.restart()
      poller(worker.cancel, worker.cancel, worker.restart, worker.restart)
    } else {
      // no side effects if poller function is not supplied
      setInterval(() => this.$fetch(key), poll.interval)
  }
}

fungl164 avatar Jan 20 '18 17:01 fungl164