Jquery autoincrement value and detect for reset

I start with value i=0, and the max value it´s 4, when script detect value it´s the same as 4 must restart or reset value of "i" to 0 as default value

i = 0;

function loading() {

  if (i == 4) {
    i = 0;
  }

  jQuery("#text").show(1000).hide(1000, function() {
    reloading();
  });
}


function reloading() {
  setInterval("loading()", 2000);
  alert("ok" + i);
  i++;
}


loading();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" style="position:relative;width:150px;height:150px;background-color:red;display:none;"></div>

I try do for show the div 4 times and reset to 0 and start other time 0,1,2,3, and reset 0 and start other time, but not works, i don´t know why happend this, i think the code it´s ok but sure something bad

Thank´s for the help in advanced

2 answers

  • answered 2018-05-16 04:25 Alive to Die

    The problem is when you called your function loading() to start the animation variable i values started from 1, not 0 and hence it goes for 3 times only and then get reset to 0.(because after 3 iterations i become 4)

    So increase 4 to 5 in if(i==4){ and you will good to go

    Working snippet:-

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="text" style="position:relative;width:150px;height:150px;background-color:red;display:none;"></div>
    
    <script>
        i=0;
        $(document).ready(function(){
            loading();
        });
        function loading(){
          if(i==5){
            i=0;
          }
          jQuery("#text").show(1000).hide(1000,function(){reloading();});
        }
        function reloading(){
          setInterval("loading()",2000);
          alert("ok"+i);
          i++;
        }
    </script>
    

  • answered 2018-05-16 04:27 Rakesh Mishra

    Code is not working because your if condition code running only when page loads. You have to call this condition on every function call Put the If condition inside function as below

    function reloading()
        {
            if(i==4)
            {
                i=0;
            }
            setInterval("loading()",2000);
            console.log("ok"+i);
            i++;
        }