I'm using MIDI.js to play a MIDI file with several musical instruments.
The following things execute too late, how can I fix that?
- First notes of the song. Like all notes, they are scheduled via
start()
of anAudioBufferSourceNode
here. - MIDI program change events. They are scheduled via
setTimeout
here. Their "lateness" is even worse than that of the first notes.
When I stop the song and start it again, there are no problems anymore, but the delay
values are very similar. So the delay
values are probably not the cause of the problem.
(I use the latest official branch (named "abcjs") because the "master" branch is older and has more problems with such MIDI files.)
That is how JavaScript Event Loop works.
Instead of
setTimeout()
you can usewindow.requestAnimationFrame()
and calculate elapsed time for delay by yourself.In our situation, we don't want to do any animation but want to just use it for a better-precision timeout.
If you run it many times, you'll see that
delay()
is pretty much all the time better thansetTimeout()
. The difference is very small because there is nothing else happens on the page. If there will be something intensive running,setTimeout()
should demonstrate worse "precision".