Skip to content

Instantly share code, notes, and snippets.

@heycarsten
Last active March 12, 2019 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heycarsten/6510386 to your computer and use it in GitHub Desktop.
Save heycarsten/6510386 to your computer and use it in GitHub Desktop.
Creates a computed property that automatically increments itself at the specified interval in milliseconds. Useful when used as a dependent property to properties that need to changed as time progresses.
/*
Creates a computed property that automatically increments itself at the
specified interval in milliseconds. Useful when used as a dependent
property to properties that need to changed based on time.
App.PostController = Ember.ObjectController.extend({
'@timer': Ember.computed.timer(1000),
sinceCreated: function() {
return new Date().getTime() - this.get('createdAt').getTime();
}.property('createdAt', '@timer')
});
*/
void function() {
var DEFAULT_INTERVAL = 5000; // 5 seconds
var cancel = Em.run.cancel,
later = Em.run.later,
get = Em.get,
set = Em.set;
function Timer(interval) {
this.interval = (interval || DEFAULT_INTERVAL);
}
Timer.prototype = {
didTick: Em.K,
isActive: false,
currentInterval: 0,
resume: function() {
if (!this.isActive) {
this.isActive = true;
this._tick();
}
},
_tick: function() {
var nextTick = later(this, function() {
this._tick();
this.currentInterval++;
this.didTick(this.currentInterval);
}, this.interval);
this._nextTick = nextTick;
}
};
Em.computed.timer = function(interval) {
var timer = new Timer(interval);
return Em.computed(function(key) {
var obj = this;
timer.didTick = function() {
obj.notifyPropertyChange(key);
}
timer.resume();
return timer.currentInterval;
});
};
}.call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment