WebMidi.js timing

edited July 2020 in Questions & Support

Thanks a lot for the project, looks exciting!

I was just curious as to how you are handling timing. I've had a quick peruse through the source and couldn't see anything in regarding something like setTimeout, which can apparently be problematic for timing midi events...

Tagged:

Comments

  • edited July 2020

    Hello Andy!

    As of now, there is no explicit handling of timing in WebMidi.js. A few people have suggested that v3 should include better time handling and I'm definitely open to suggestions (which should be submitted in the Enhancement Proposals section of this forum).

    Basically, as of v2.5.1, you can schedule events by specifying a DOMHighResTimeStamp representing the number of milliseconds that passed since the time origin . The origin basically is the time when the script was started. The timestamp is in milliseconds and decimals can be used. According to the DOMHighResTimeStamp documentation, the time should be accurate to 5 µs (microseconds).

    So, for example, to schedule an event one second in the future, you can use WebMidi.time + 1000 for the time option:

    WebMidi.output[0].playNote("C3", 1, {time: WebMidi.time + 1000};
    

    Since this is fairly common, you can also pass a string starting with a + sign to achieve the same result:

    WebMidi.output[0].playNote("C3", 1, {time: "+1000"};
    

    Various methods have a time option and it always works in the same way. By the way, WebMidi.time is simply an alias to performance.now().

    As far as setTimeout() or setInterval() go, they really aren't accurate enough. Chris Wilson wrote a detailed article on the subject should you want to know more.

    Having said all that, I'd love to know what your use case it and how WebMidi.js could simplify time handling.

    Cheers! 🤘

  • Well, I appreciate the very detailed answer!

    I'm planning to make my own web based midi sequencer, hence the time in question.

    It's good to hear you've taken accuracy into consideration so I'll be looking more deeply into your API, and your responses above.

    Thanks again 🙂