4

For fun, I've built a simple simulation of a drum machine in JavaScript. (You can try it at http://mink.click .)

I'm wondering if there's anything I can do to improve the accuracy of setInterval(...). In a perfect world, a sample would fire every 250 ms (until I make it customizable). But (a) running code stops it from being a perfect world, because it takes time to execute each instruction, and (b) sometimes, when I've just started playing, the firing of the timer (in Chrome) seems to take longer.

I know that in Windows, you can set a multimedia timer that's more accurate than the typical WM_TIMER messages, which use the message queue. So, I'm wondering if there's any way of getting a more accurate timer in JavaScript.

I know JavaScript isn't the best place to build a drum machine simulator, but I'm just doing it for fun :-)

themink
  • 827
  • 1
  • 6
  • 8
  • 1
    Consider [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) - note, you don't control the frequency this is called, but with a little reorganisation of your code, it could be what you need – Jaromanda X Jan 16 '18 at 02:55
  • 2
    Have a look at [How to create an accurate timer in javascript?](https://stackoverflow.com/q/29971898/1048572) - it proposes a way to prevent drift, but you cannot guarantee a perfect interval. – Bergi Jan 16 '18 at 02:55
  • 1
    ^ It explains two ways to improve accuracy. Using setTimeout and date() to adjust the interval drifting, and also using a smaller timeOut than the target so you have another chance to fix it. – JasonB Jan 16 '18 at 02:59

0 Answers0