Help setTimout in a loop

I have trouble to understand the variable passed in setTimeout()
I didn’t declare ‘y’ variable passed in setTimout()
then ‘y’ replace ‘x’ in the execution, then I’m using x to iterate?
The code works as is expected.

var list = [1,2,3,4];
for (var x = 0, ln = list.length; x < ln; x++) {
  setTimeout(function(y) {    
    console.log("%d => %d", y, list[y] += 10);
  }, x * 500, x); // we're passing x
}

According to the documentation here, setTimeout accepts the following parameters:
window.setTimeout(func[, delay, param1, param2, ...]);

So, the 2nd parameter that you’re passing to setTimeout is the delay, which you’ve defined as x * 500. The 3rd parameter, x, is passed into the function as y.

I hope that clears it up a little. :slight_smile:

thanks, why x * 500 ?
without x I don’t have the right time.

It looks to me like this code makes 4 calls to setTimeout in the for loop:

First iteration, x = 0, the function in setTimeout will be called immediately, since 0 * 500 = 0ms delay.
Second iteration, x = 1, the function in setTimeout will be called in 500ms.
Third iteration, x = 2, the function in setTimeout will be called in 1000ms.
Fourth iteration, x = 3, the function in setTimeout will be called in 1500ms.
In the next iteration, x = 4, and is no longer < list.length, so the for loop exits.

1 Like

all of the iterations of the loop are performed in the same time, so if the delay would be a constant value, all logs would happen in the same time, ie. after 500ms. Because there is variable x in the delay, the first setTimeout is set to 0, second to 500, third to 1000, and fourth to 1500, which makes logs happen in 500ms intervals.

A synchronous version of setTimeout would look like this:

function setTimeout(fnToBeCalledAfterDelay, delay, ...paramsToBePassedToFn) {
    const timeToExecuteFn = Date.now() + delay

    while (timeToExecuteFn > Date.now()) {
  	  //block
    }

    fnToBeCalledAfterDelay(...paramsToBePassedToFn)
}
1 Like

I did something for Simon Game:
Work well !

  as.forEach(function (cle, i, origin) {
    anim = setTimeout(function(i) { // i is replace by j   
      for (let prop in data){
        if (data.hasOwnProperty(prop)) {
          if (prop === dataGame[cle].color) {
            setTimeout(function () {
              showShape()
              $('.'+prop).addClass('active')
              _playSound(dataGame[cle].sound)
            }, 2000)
            setTimeout(function () {
              //hideShape()
              console.log('removeActiveClass');
              removeActiveClass()
            }, 2500)
          }
        }
      } //end forin
      if (as.length-1  === i) {
        clearTimeout(anim)
        setTimeout(function () {
          addOneStep()
          return this
        }, 1000);//1s
      }
    }, i * 1000, i); // we're passing i in the argument of the callBack
  });
1 Like

console.log("%d => %d")
Someone have the link or explain to understand this syntaxes?
Thanks