Skip to content

Instantly share code, notes, and snippets.

@beckyconning
Created October 28, 2012 22:37
Show Gist options
  • Save beckyconning/3970224 to your computer and use it in GitHub Desktop.
Save beckyconning/3970224 to your computer and use it in GitHub Desktop.
Crafty.c("Metronome", {
_bpm: 85,
_resolution: 64,
_beatsPerBar: 4,
_period: function() {
var beatPeriod = (60000 / this._bpm) / (this._resolution / this._beatsPerBar);
return beatPeriod;
},
_startTime: 0,
_timeNow: 0,
_ticksElapsed: '0.0',
init: function() {
this._startTime = new Date().getTime();
this._tick();
},
_tick: function() {
Crafty.trigger("MetronomeTick");
this._timeNow += this._period();
this._ticksElapsed = Math.floor(this._timeNow / this._period()) / 10;
if(Math.round(this._ticksElapsed) == this._ticksElapsed) { this._ticksElapsed += '.0'; }
var difference = (new Date().getTime() - this._startTime) - this._timeNow;
var thisMetronome = this;
window.setTimeout(function() { thisMetronome._tick(); }, (this._period() - difference));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment