1

Working out a BPM function in JS, where I'm playing a short sound for x times in one minute.

But it's not working for me, and this is what I have. Can't find anything on this either.

The math should be simple: L*BPM/M, Length * How many times / 60 seconds.

I have tried with something like this:

var length = 0.5;
var bpm = 60;
var minute = 60;

for(var i = 0; i < bpm; i++) {
  setTimeout(function() {
    console.log('test');
  }, ((length*bpm) / minute * 1000 ) * i);
}
Marius Djerv
  • 267
  • 1
  • 4
  • 18
  • 1
    So what is wrong? – Justinas Mar 30 '17 at 10:34
  • 2
    Have a look on this: http://stackoverflow.com/questions/729921/settimeout-or-setinterval. Altough one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish. – xszaboj Mar 30 '17 at 10:34
  • It's not working correctly. It's counting to fast, so the math is off. – Marius Djerv Mar 30 '17 at 10:35
  • Thanks @xszaboj! Okey, will try it out @callback. But is the math correct tho? – Marius Djerv Mar 30 '17 at 10:38
  • do you want to trigger the function every second for a minute? – callback Mar 30 '17 at 10:53
  • Yeah, I want to play a sound x times in one minute. So let's say that BPM is 90, I should play the sound 90 times in 60 seconds. Nothing more or less. And that's when the length of the audio comes in (I think). I need to spread out the audio with equal delay in one minute. (Repeat) – Marius Djerv Mar 30 '17 at 11:00

1 Answers1

1

The math should be: (60 / bpm) * 1000

I don't know what the length variable is, you didn't explain it. The following will cause the "test" to run 180 times in a minute

var bpm = 180;
var interval = (60 / bpm) * 1000;
var ranTimes = 0;
var myTimeout = setInterval(function() {
    console.log('test' + ranTimes);
    ranTimes++;
    if (ranTimes >= bpm) {
        clearInterval(myTimeout);
    }
}, interval);
AlexD
  • 4,062
  • 5
  • 38
  • 65
  • The length was the length of the audio file, but I figured that I didn't need it in my project. But this is what I ended up with! Thanks :D – Marius Djerv Mar 30 '17 at 11:18