Created
August 4, 2015 10:49
-
-
Save tzhbami7/982698edca77052f3f9e to your computer and use it in GitHub Desktop.
EmberJS CountDown with Ember.run.later()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Ember from 'ember'; | |
export default Ember.Object.extend({ | |
interval: function() { | |
return 10; // Time between polls (in ms) | |
}.property().readOnly(), | |
totalTime: function() { | |
return 5000; // Total Time (in ms) | |
}.property(), | |
timeDiff: 0, | |
timeLeft: function() { | |
return Math.floor((this.get('totalTime') - this.get('timeDiff')) / 1000); | |
}.property('timeDiff'), | |
hasFinished: function() { | |
return this.get('timeLeft') === 0; | |
}.property('timeLeft'), | |
// Schedules the function `f` to be executed every `interval` time. | |
schedule: function(f) { | |
return Ember.run.later(this, function() { | |
f.apply(this); | |
this.set('timer', this.schedule(f)); | |
}, this.get('interval')); | |
}, | |
// Stops the countdown | |
stop: function() { | |
Ember.run.cancel(this.get('timer')); | |
}, | |
// Starts the countdown, i.e. executes the `onTick` function every interval. | |
start: function() { | |
this.set('startedAt', new Date()); | |
this.set('timer', this.schedule(this.get('onTick'))); | |
}, | |
onTick: function() { | |
let self = this; | |
self.set('timeDiff', new Date() - self.get('startedAt')); | |
if (self.get('hasFinished')) { | |
// TODO: Should cancel the counter but doesn't work | |
// Ember.run.cancel(); | |
// self.stop(); | |
// Ember.run.cancel(self.get('timer')); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment