Home > Mobile >  How can I set a for loop with settimeout that iterates backwards?
How can I set a for loop with settimeout that iterates backwards?

Time:12-05

I may be approaching this in completely the wrong way, as I'm a bit of a novice when it comes to javascript, but essentially what I'm trying to do (for a bit of fun) is to have a cell of a table change colour onclick, then have the cells to the north, east, south, and west change to a different colour in sequence (think of the bomb effect in bomberman).

So far, I've managed to get the south direction to work using the following code:

function timeOutDown(i) {
  let bubbleRowPositive = col   rowArray[i];
  let bubbleRowPositiveId = document.getElementById(bubbleRowPositive);

  setTimeout(function() {
    bubbleRowPositiveId.style.backgroundColor = "#AA3333";
  },i * 50);
}

for (let i=row; i<colArray.length; i  ) {
  timeOutDown(i);
}

For context, there are 15 rows and 15 columns of evenly sized table cells, with ID's like "a1" and "h14".

However, the issue I'm coming across is that the inverse will still iterate upwards, even when reversing the for loop and I can't figure out why:

function timeOutUp(k) {
  let bubbleRowNegative = col   rowArray[k];
  let bubbleRowNegativeId = document.getElementById(bubbleRowNegative);

  setTimeout(function() {
    bubbleRowNegativeId.style.backgroundColor = "#AA3333";
    console.log(`Index: ${k}, Row Num: ${rowArray[k]}`);
  },k * 50);
}

for (let k=row-2; k>=0; k--) {
  timeOutUp(k);
  console.log(k);
}

I had started by using the same function to handle both for loops, that didn't work, so I attempted this method using 2 separate functions.

Is there an easier way to go about this?

CodePudding user response:

Even though your for loop reversed, it still passes in the same index for every iteration, and that index is used to compute the delay it gets. So no matter what, the item at index 0 gets 0*50 milliseconds delay, regardless whether it happens first or last. You still need your original counter in order to define their ordered index. You could solve it like this:

function timeOutUp(k, i) {
  let bubbleRowNegative = col   rowArray[k];
  let bubbleRowNegativeId = document.getElementById(bubbleRowNegative);

  setTimeout(function() {
    bubbleRowNegativeId.style.backgroundColor = "#AA3333";
    console.log(`Index: ${k}, Row Num: ${rowArray[k]}`);
  },i * 50);
}

for (let k=row-2, i = 0; k>=0; k--, i   ) {
  timeOutUp(k, i);
  console.log(k, i);
}

I just added 1 variable: i back in, that counts up. It gets passed to timeOutUp to compute the actual delay in the order you intend.

  • Related