javascript - Why is setInterval only executed once?
黄舟
黄舟 2017-06-30 09:55:19
0
7
980
  • Simple background switching

jquery part

$(function(){
            
            function direct(){
                
                for(var i=0;i<2;i++){
                $(".bg_img").eq(i).show().siblings().hide();
                }
            }

            setInterval(direct,1000);
        })

html section

<p class="main_bg">
        <p class="bg_img bg1"></p>
        <p class="bg_img bg2"></p>
    </p>

css part

.bg2 default display:none;

  • setInterval() has only been executed once, so I would like to ask why it cannot be entered a second time?

Dear bosses, please don’t despise me, thank you for your answers~

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(7)
ringa_lee

Not to despise you, but this is obviously a syntax problem... In fact, I think setInterval is always executed, but the running result of your function direct is fixed. The final result of the loop is that the second picture is displayed and the first picture is hidden. , so it looks like it's not executed.

You should do this:

var current = 0;
function direct(){
  $(".bg_img").eq(current).show()
    .siblings().hide();
  current++;
  if (current > 1) {
    current = 0;
  }  
}

A closure is used here to save the state outside the timer so that it can be looped down each time.

In addition, add some knowledge about rendering. For this kind of for loop to change the view state, the browser will cache these states and then render them at an appropriate time, instead of rendering them immediately as soon as you modify it. So you can't even see it flash.

学习ing

Please refer to it

$(function(){
  function direct(i){
    $(".bg_img").eq(i).show().siblings().hide();
  }

  var i = 0;
  setInterval(function () {
    direct(i)
    i = (i + 1) % $(".bg_img").length
  }, 1000);
})
習慣沉默

setInterval(function direct(){

            
            for(var i=0;i<2;i++){
            $(".bg_img").eq(i).show().siblings().hide();
            }
        },1000);
      直接这样试试,控制台看看,有没有报错,如果报错的话,js也不会继续执行了的。
滿天的星座

After looping once, the value of i is 1 and then it remains 1. Try using let

过去多啦不再A梦

Do you want this effect to be displayed one by one in order?

jQuery(function($){
    var bgImg = $(".bg_img"),
        maxIndex = bgImg.length - 1,
        i = 0;

    function direct(){
        bgImg.eq(i).show().siblings().hide();

        if (i < maxIndex) {
            i++;
        } else {
            i = 0;
        }
    }

    setInterval(direct, 1000);
});
为情所困

$(function(){

var index = 0;
setInterval(function(){
    (index < $('.bg_img').length) ? index ++ : index = 0;
    $('.bg_img').eq(index).show().siblings().hide();
},1000);

})

滿天的星座
setInterval(direct(),1000);

I don’t know if it’s right, but I always feel that this is the problem

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