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.
To cancel the execution, we should call clearTimeout/clearInterval with the value returned by setTimeout/setInterval . Nested setTimeout calls are a more flexible alternative to setInterval , allowing us to set the time between executions more precisely.
The difference between setTimeout() and setInterval() is that setTimeout() triggers the function call once. While, the setInterval() triggers the function repeatedly after the specified interval of time. Let us look at a small example to understand the setInterval function.
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.
setInterval and setTimeout are two of the higher order functions in Javascript.
You can create a setTimeout
loop using recursion:
function timeout() { setTimeout(function () { // Do Something Here // Then recall the parent function to // create a recursive loop. timeout(); }, 1000); }
The problem with setInterval()
and setTimeout()
is that there is no guarantee your code will run in the specified time. By using setTimeout()
and calling it recursively, you're ensuring that all previous operations inside the timeout are complete before the next iteration of the code begins.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With