How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

I am working on a music program that requires multiple JavaScript elements to be in sync with another. I’ve been using setInterval, which works really well initially. However, over time the elements gradually become out of sync which is bad in a music program.

I’ve read online that setTimeout is more accurate, and you can have setTimeout loops somehow. However, I have not found a generic version that illustrates how this is possible.

Basically I have some functions like such:

//drums
setInterval(function {
  //code for the drums playing goes here
}, 8000);

//chords
setInterval(function {
  //code for the chords playing goes here
}, 1000);

//bass
setInterval(function {
  //code for the bass playing goes here
}, 500);

It works super well, initially, but over the course of about a minute, the sounds become noticeably out of sync as I’ve read happens with setInterval. I’ve read that setTimeout can be more consistently accurate.

Could someone just show me a basic example of using setTimeout to loop something indefinitely? Alternatively, if there is a way to achieve more synchronous results with setInterval or even another function, please let me know.

Leave a Comment