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

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


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.


Only to supplement. If you need to pass a variable and iterate it, you can do just like so:

function start(counter){  if(counter < 10){    setTimeout(function(){      counter++;      console.log(counter);      start(counter);    }, 1000);  }}start(0);

Output:

123...910

One line per second.


Given that neither time is going to be very accurate, one way to use setTimeout to be a little more accurate is to calculate how long the delay was since the last iteration, and then adjust the next iteration as appropriate. For example:

var myDelay = 1000;var thisDelay = 1000;var start = Date.now();function startTimer() {        setTimeout(function() {        // your code here...        // calculate the actual number of ms since last time        var actual = Date.now() - start;        // subtract any extra ms from the delay for the next cycle        thisDelay = myDelay - (actual - myDelay);        start = Date.now();        // start the timer again        startTimer();    }, thisDelay);}

So the first time it'll wait (at least) 1000 ms, when your code gets executed, it might be a little late, say 1046 ms, so we subtract 46 ms from our delay for the next cycle and the next delay will be only 954 ms. This won't stop the timer from firing late (that's to be expected), but helps you to stop the delays from pilling up. (Note: you might want to check for thisDelay < 0 which means the delay was more than double your target delay and you missed a cycle - up to you how you want to handle that case).

Of course, this probably won't help you keep several timers in sync, in which case you might want to figure out how to control them all with the same timer.

So looking at your code, all your delays are a multiple of 500, so you could do something like this:

var myDelay = 500;var thisDelay = 500;var start = Date.now();var beatCount = 0;function startTimer() {        setTimeout(function() {        beatCount++;        // your code here...        //code for the bass playing goes here          if (count%2 === 0) {            //code for the chords playing goes here (every 1000 ms)        }        if (count%16) {            //code for the drums playing goes here (every 8000 ms)        }        // calculate the actual number of ms since last time        var actual = Date.now() - start;        // subtract any extra ms from the delay for the next cycle        thisDelay = myDelay - (actual - myDelay);        start = Date.now();        // start the timer again        startTimer();    }, thisDelay);}