title: How to add and remove class in a loop with jQuery
body: <p>I have a 3 by 3 grid.
  Red class needs to be added to my grid cells. It has to be continue from cell1 to cell 9, once it reaches cell9, it should start from cell1 again. At position cell2, it has to check if cell1 has red class, if so remove it and add "red" class to the cell2 and this process should continue forever.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
  
      // setInterval(AddRedClass(), 1000)
  
  });
  
  function AddRedClass() {
      var boxes = $('.box');
      var boxLength = boxes.length - 1;
      var lastChildIndex;
  
      for (var index = 0; index &lt; boxLength;) {
  
          var currentBox = $(boxes[index]);
          var lastChildIndex = (index == 0) ? boxLength : index - 1;
          var prevBox = $(boxes[lastChildIndex]);
  
          if (prevBox.hasClass('red'))
              setTimeout(prevBox.removeClass('red'), 1000);
  
          setTimeout(currentBox.addClass('red'), 1000);
          index = (index + 1) % boxLength;
      }
  
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      width: 250px;
  }
  
  .box {
      width: 30%;
      border: 1px solid green;
  }
  
  .red {
      background: red!important;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div class="container"&gt;
          &lt;div class="box"&gt;
              c-1
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-2
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-3
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-4
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-5
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-6
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-7
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-8
          &lt;/div&gt;
          &lt;div class="box"&gt;
              c-9
          &lt;/div&gt;
      &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Can someone please explain what is wrong with my code.</p>
  
  <p>Thanks</p>