search

Home  >  Q&A  >  body text

javascript setInterval() function

Use the setInterval() function to dynamically add css to li

<ul>
    <li> 1 </li>
    <li> 2 </li>
    <li> 3 </li>
    <li> 4 </li>
  </ul>
var i = -1;
setInterval(function(){
  i++;.
  console.log(i);
  (i > 3) ? i = -1 : changeClass(i);

}, 1000);

function changeClass(j) {
  $('li').eq(j).addClass('cur').siblings().removeClass('cur');
}

It is found that the change of i is 0->1->2->3->4->0->1->2->3->4, which means After adding css to the li with subscript 3, there will be an interval of 1s before dynamic switching continues, because there is no li with subscript 4. What is causing this?

为情所困为情所困2748 days ago500

reply all(5)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:14:53

    Because (i > 3) ? i = -1 : changeClass(i); ternary operation,

    When i=4 (i > 3) ? Does it mean that 4 is greater than 3? , if 4 is definitely greater than 3, execute i = -1,

    The function changeClass(i) will not be executed, so there is no li with subscript 4

    reply
    0
  • 某草草

    某草草2017-05-19 10:14:53

    i大于3的时候,i=-1了。同时这次没有执行changeClass(i)
    if(i > 3) i = 0;changeClass(i)

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:14:53

    0 - 3 is already 4. Only when you write (i > 3) will it become -1, which means it has to be run five times before it becomes -1;
    If you want to run it 4 times, it will become -1 -1 should be changed to (i >= 3)

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:14:53

    if(i<3){
        changeClass(i);
    }else{
        changeClass(i);
        i = -1 
    }

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:14:53

    The fourth one can never be hung up, so it is recommended to change i>3 to i>4 or i>=3

    reply
    0
  • Cancelreply