简体   繁体   中英

setInterval is working once in Chrome but fine in other browsers

I have the following slideshow code:

HTML

<div id="slideshow"><img src="common/images/background/Slide1b.jpg" />
   <img src="common/images/background/Slide2b.jpg" />
   <img src="common/images/background/Slide3b.jpg" />
   <img src="common/images/background/Slide4b.jpg" />
</div>

jQuery

var opt1 = 1;
$(document).ready(function() {

    $('#slideshow').supersize();
    all_images = $('#slideshow > img');
    all_images.hide();

    first = $('#slideshow > img:eq(0)');
    first.show().attr('class', 'power');

    setInterval(function() { 
        var total = $('#slideshow > img').length;

            if(opt1 < total) {
                var current = $('.power');
                var next = $('.power').next();              

                current.removeClass('power').fadeOut('slow');
                next.fadeIn('slow').addClass('power');

                ++opt1;
            } else {
                opt1 = 1;
                all_images.removeClass('power').fadeOut('slow');
                first.addClass('power').fadeIn('slow');             
            }
    }, 2000);       

});

It is working fine in all other browsers except in Google Chrome it fires only once.

This is a working answer, I dont know why chrome likes setTimeout better then setInterval, but it does. I also use .animate instead of .fadeIn and .fadeOut.

$(document).ready(function()
{
    $('#slideshow').supersize();
    var images = $('#slideshow>img');
    images.css('opacity', 0)

    var first = images.eq(0);
    first.css('opacity', 1).addClass('power');

    setTimeout(on_timer, 2000);

    function on_timer()
    {
       var current = $('.power');
       var next = $('.power').next();       

       if (next.length == 0)
          next = first;

       current.removeClass('power').animate({opacity: 0}, 1000);
       next.css('opacity', 0).animate({opacity: 1}, 1000).addClass('power');

       setTimeout(on_timer, 2000);
    }
});

Demo on

http://62.168.145.82/slideshow/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM