Created
October 5, 2015 05:04
-
-
Save Digikid13/79d250918b2973bb8f68 to your computer and use it in GitHub Desktop.
Accurate BPM timer
This file contains 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
/** | |
* This code is based off http://www.sitepoint.com/creating-accurate-timers-in-javascript/ | |
* This is my adaptation to make it work with bpm, using this you can create abstract timers that are based off other measures | |
*/ | |
// bpm is the number of beats in a minute | |
var bpm = 128; | |
// stop is just a var to let you stop the loop from continuing manually | |
var stop = false; | |
var start = new Date().getTime(), | |
time = 0, | |
// step is calculating how many milliseconds per beat | |
step = 60000 / bpm; | |
function beat() { | |
/** | |
* Do your action per beat here | |
**/ | |
// time is incremented by step we use this to compare against the start time | |
time += step; | |
// the difference is based off the current time - start time - time expected | |
// this allows us to get a millisecond different and adjust the timeout below to be accurate | |
var diff = (new Date().getTime() - start) - time; | |
// this is where the stop variable comes in, we can manually inject 'stop = true;' into the console to stop the loop | |
if (!stop) window.setTimeout(beat, (step - diff)); | |
} | |
// we start the beat loop | |
window.setTimeout(beat, step); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment