Skip to content

Instantly share code, notes, and snippets.

@voltidev
Created December 12, 2014 12:34
Show Gist options
  • Save voltidev/1a21ec15d6953a067802 to your computer and use it in GitHub Desktop.
Save voltidev/1a21ec15d6953a067802 to your computer and use it in GitHub Desktop.
import Ember from 'ember';
var Pollster = Ember.Object.extend({
// Time between polls (in milliseconds).
interval: 5000,
// Schedules the function `func` to be executed every `interval` time.
schedule: function(func) {
var interval = this.get('interval');
var isPolling = this.get('isPolling');
if (!isPolling) {
return;
}
return Ember.run.later(this, function() {
func.apply(this);
this.set('timer', this.schedule(func));
}, interval);
},
// Stops the pollster
stop: function() {
Ember.run.cancel(this.get('timer'));
this.set('isPolling', false);
},
// Executes the `onPoll` function at specified interval.
start: function() {
var onPoll = this.get('onPoll');
var isPolling = this.get('isPolling');
if (isPolling) {
return;
}
this.set('isPolling', true);
this.set('timer', this.schedule(onPoll));
},
// Must be implemented by the user.
onPoll: function(){
}
});
/**
It's a replacement for setInterval that relies on `Ember.run.later`
The startPollster() calls the passed target/method at specified intervals
(in milliseconds). It will continue calling the target/method until
pollster.stop() is called.
You can use it whenever you need to run some action at specified interval
instead of using setInterval(). It will ensure that items that expire during
the same script execution cycle all execute together, which is often more
efficient than using a real setInterval.
Examples:
```javascript
var pollster = startPollster(10000, user, user.reload);
pollster.stop();
```
```javascript
var pollster = startPollster(5000, function() {
// <...>
if (count === 5) {
pollster.stop();
}
});
```
```javascript
var pollster = Pollster.create({
interval: 15000,
onPoll: function() {
user.reload();
}
});
pollster.start();
```
@param {Number} interval Number of milliseconds.
@param {Object} [target] target Context of the method to invoke.
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@return {Object} Pollster instance for use in stopping.
*/
function startPollster(interval, target, method) {
if (!method) {
method = target;
target = null;
}
if (typeof method === 'string') {
method = target[method];
}
var pollster = Pollster.create({
interval: interval,
onPoll: function() {
method.apply(target);
}
});
pollster.start();
return pollster;
}
export { Pollster, startPollster };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment