Problems with the time interval in a carousel

0

Well, I'm having some problems with a carousel created by myself, more specifically in the transition order of the items.

var carouselBannerHolder = document.getElementById("banners-slider");
var itemsCarousel = document.querySelectorAll(".banners-slider figure");
var count = 0;    
carouselBannerHolder.style.width = (parseInt(itemsCarousel.length)) + "00%";

function ordemComumSlide(){
    setInterval(function(){
        if(count < itemsCarousel.length){
            carouselBannerHolder.style.left = ("-" + count + "00%");
            count++;
        }else{
            return count = 0;
        }
    },2500);
};
ordemComumSlide();

On the first slide, it takes twice as long when the page starts, then it works normally, how can I fix it? is there anything in the code that I can improve on?

    
asked by anonymous 21.03.2017 / 13:23

1 answer

2

At bottom, what happens with the first round is that it will do the following:

carouselBannerHolder.style.left = ("-000%");

Because the count is still 0 , ie this turn apparently takes twice the time of the others, start and reset the count to 1:

count = 1;
...
else {
     carouselBannerHolder.style.left = ("0");
     count = 1;
}
...

And I think it gets resolved, eg:

var len = 3;
var count = 1;
function ordemComumSlide(){
    setInterval(function(){
        if(count < len){
           console.log("-" + count + "00%");
           count++;
        }else{
           console.log("0");
           count = 1;
        }
    },1500);
};
ordemComumSlide();

You can also opt for another approach, I would do this:

var len = 3;
var count = 0;
function ordemComumSlide(){
    setInterval(function(){
        count++;
        if(count >= len){
           count = 0;
        }
        //carouselBannerHolder.style.left = ("-" + count + "00%");
        console.log("-" + count + "00%");
    },1500);
};
ordemComumSlide();
    
21.03.2017 / 13:36