Javascript switch statement not working properly cant find solution

I’m working on a new project but have some issues with this bit of javascript. I cant figure out what is wrong and hope you can help me.

What I want my peice of code to do is count var i to 4, when it hits 4 set i to 0 and start again. The issue is that the switch statement only executes case 0 eventhough i is set to 1. I tried switching everything to strings but doesnt seem to help.

function bckLoad() {
  var i = 0;

  switch (i) {
    case 0:
      i = 1;
      var leftPos = $('#index-header').scrollLeft();
      $("#index-header").animate({
        scrollLeft: leftPos + 1940
      }, 800);
      window.alert("Test");
      break;
    case 1:
      i = 2;
      var leftPos = $('#index-header').scrollLeft();
      $("#index-header").animate({
        scrollLeft: leftPos + 1940
      }, 800);
      window.alert("test1");
      break;
    case 2:
      i = 3;
      var leftPos = $('#index-header').scrollLeft();
      $("#index-header").animate({
        scrollLeft: leftPos + 1940
      }, 800);
      window.alert("test2");
      break;
    case 3:
      i = 4;
      var leftPos = $('#index-header').scrollLeft();
      $("#index-header").animate({
        scrollLeft: leftPos + 1940
      }, 800);
      window.alert("test3");
      break;
    case 4:
      i = 0;
      var leftPos = $('#index-header').scrollLeft();
      $("#index-header").animate({
        scrollLeft: leftPos - 7760
      }, 800);
      window.alert("test4");
      break;
    default:
      break;
  }
}
var intervalID = window.setInterval(bckLoad, 6000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="index-header">
  <ul>
    <li>
      <a href="#">
        <h1>Home</h1>
      </a>
    </li>
    <li>
      <a href="#">
        <h1>Blog</h1>
      </a>
    </li>
    <li>
      <a href="#">
        <h1>About</h1>
      </a>
    </li>
    <li>
      <a href="#">
        <h1>Contact</h1>
      </a>
    </li>
  </ul>
</div>

Answer

Move

 var i = 0;

outside of the function. Otherwise it will be reset every time.

How I would do that:

  const leftBy = [1940, 1940, 1940, -7760];
  let i = 0;

  function animate() {
    const leftPos = $('#index-header').scrollLeft();
    $("#index-header").animate({scrollLeft: leftPos + leftBy[i]}, 800);                       
    window.alert(`Test${i}`);
    i = (i + 1) % 5;
  }

  setInterval(animate, 6000);

Leave a Reply

Your email address will not be published. Required fields are marked *