javascript setInterval() function
为情所困
为情所困 2017-05-19 10:12:53
0
5
523

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?

为情所困
为情所困

reply all(5)
伊谢尔伦

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

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

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)

仅有的幸福
if(i<3){
    changeClass(i);
}else{
    changeClass(i);
    i = -1 
}

仅有的幸福

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template