简体   繁体   中英

setInterval issue with image not loading immediatly

I have created a slideshow involving images which will change in accordance to the setInterval method I am using. Previously, I was having some issues with the timing of the setInterval whenever I would leave the page for a while, go to another tab or window, and then return. The slideshow timing would not flow correctly when I returned to the page - the timing of the changes were just off and as a result the jquery effects were firing at the wrong time as well.

I have now managed to at least fix that particular issue due to adding a hasFocus condition.

However, what I am finding to be the issue now, is that when I do return to the page, there is no image where the slideshow is placed. I have to wait the 6 seconds applied to the interval function.

Any idea on how I can guarantee one of the images is always displayed on the page when the user returns to the window?

 var bannerImages = [ "banner1.jpeg", "banner2.jpg", "banner3.png" ]; var currentImage = 1; $(".banner-img").fadeIn(500).delay(5000).fadeOut(); setInterval(function(){ if (currentImage > bannerImages.length-1){ currentImage = 0; } if (document.hasFocus()) { $(".banner-img").fadeIn().attr("src",bannerImages[currentImage]).delay(5000).fadeOut(); currentImage++; } }, 6000) 
 <section id="banner"> <div class="row"> <div class="col-md-12"> <img src="http://via.placeholder.com/350x150" class="img-responsive center-block banner-img"> </div> </div> </section> 

Your code does not wait for the fadeIn animation to finish before changing the src attribute and fading out. I suggest a bit different logic, like this:

var bannerImages = [
    "banner1.jpeg",
    "banner2.jpg",
    "banner3.png"
];

var currentImage = 1;

//$(".banner-img").fadeIn(500).delay(5000).fadeOut(); //I don't think you need this.

setInterval(function(){
    if (document.hasFocus()) {
        $(".banner-img").fadeOut(100, function() {
            $(".banner-img")
                .attr("src", bannerImages[++currentImage % bannerImages.length])
                .fadeIn(100);
        });
    } 
}, 6000);

See this post for what that callback function is for: How to get jQuery to wait until an effect is finished?

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