0

could somebody help me to fully understand what is happening here please

let slideShowHandler = () => {
    for(let i = 1; i <= mainElement.children.length; i++){
      setTimeout(function(){
        document.querySelector('#wrapper div:nth-of-type('+ i +')').style.display = "flex";
      }, 3000 * i);
      if(i == mainElement.children.length){
        alert(i)
      }
    }
    }

when I run the function, the alert comes up before all of the div's are displayed. I thought that it was waiting 3000ms * i and then updating i. but it looks like i goes to 4 and then the setTimeout function starts. Any explanation to how exactly this is working would be fantastic

  • 2
    setTimeout is asynchronous, so that block of code runs around 3 seconds(for the first iteration) after your alert pops up – enf0rcer Apr 08 '18 at 20:24
  • You might also be interested in [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) – E. Sundin Apr 08 '18 at 20:25
  • Without a blocking alert that loop will complete in just a couple of milliseconds. The timouts will run later – charlietfl Apr 08 '18 at 20:26
  • @Nina I was thinking about that dupe, but I think we need one that explains how asynchronous functions are non-blocking. – Bergi Apr 08 '18 at 20:33
  • @Bergi, you can reopen this question, if you need it. the alert takes later place where the loop has ended. – Nina Scholz Apr 08 '18 at 20:36
  • @NinaScholz I didn't mean to reopen, just add a dupe about `setTimeout` doing scheduling instead of sleeping. (The one I added now is just the first I could find, not a particularly good one) – Bergi Apr 08 '18 at 20:56

1 Answers1

0

The function setTimeout is non-blocking and asynchronous. That is, it executes, and registers the callback function, and then happily continues to the next statement.

Jason
  • 15,915
  • 3
  • 48
  • 72