2

I have a similar issue to Property of `this` is undefined inside a setTimeout where I'm losing a reference inside a setTimeout, but in my case I'm not using this and am already using an in-line arrow function.

I want to clear a series of 22 divs with a brief delay between each, sort of like knocking over a line of dominoes. When I do it without a delay it works fine:

function restart() {
  for (var j = 1; j < 23 ; j++) {
    document.getElementById('cabin'+j+'description').innerHTML = '';
  }
}

However when I try to add a timeout:

function restart() {
  for (var j = 1; j < 23 ; j++) {
    setTimeout(() => {
      document.getElementById('cabin'+j+'description').innerHTML = '';
    }, 50);
  }
}

It fails with "Cannot set property 'innerHTML' of null"

Any insight would be appreciated.

wilkinsm
  • 21
  • 1

1 Answers1

1

the problem is that when the function was executed, the variable j no longer exists, because it was executed after 50 ms, and the cycle to end much earlier

Reynier Rivero
  • 2,042
  • 2
  • 8
  • 12