Iterating through an array of divs

Im still new at javascript ive been learning the concepts for several months and this is my first time taking a crack at it.

Im trying to create a carousel using css3 and Javascript (no Jquery)

the console keeps throwing an error.

Uncaught TypeError: Cannot read property display of undefined

The following is my html and javascript code

var slideShow = document.querySelectorAll('.inside');

for (var i = 0; i < slideShow.length; i++) {
  setTimeout(function() {
    slideShow[i].display.style = 'inline-block';
  }, 2000)
}
<div class="inside">
  <div class="inner1">
  <h1>This is Inner div 1</h1>
  </div>
  <div class="inner2">
  <h1>This is Inner div2</h1>
  </div>
  <div class="inner3">
  <h1>This is Inner div3</h1>
  </div>
  <div class="inner4">
  <h1>This is Inner div4</h1>
  </div>
</div>

solution

Aside from display and style being in the wrong order, the problem is that by the time the setTimeout callback function is executed, the for loop has already ended, and i is equal to the length of the nodeList (and since the last element’s index is one less than the length of the nodeList, an error is thrown).

You could capture the value of i in an IIFE:

Example Here

var slideShow = document.querySelectorAll('.inside');

for (var i = 0; i < slideShow.length; i++) {
  (function (i) {
    setTimeout(function () {
      slideShow[i].style.display = 'inline-block';
    }, 2000 * (i + 1));
  })(i);
}

or you could use the .forEach() method:

Example Here

var slideShow = document.querySelectorAll('.inside');

Array.prototype.forEach.call(slideShow, function (el, i) {
  setTimeout(function () {
    el.style.display = 'inline-block';
  }, 2000 * (i + 1));
});

Alternatively, you could just use setInterval:

Example Here

var slideShow = document.querySelectorAll('.inside');
var i = 0;
var interval = setInterval(function () {
  if (i < slideShow.length) {
    slideShow[i].style.display = 'inline-block';
    i++;
  } else {
    clearInterval(interval);
  }
}, 2000);