Search code examples
javascriptclassloopssetintervaltiming

loop class in divs with different time javascript


i need to change class of current element, in loop but with different timing.

in this case it happen just once :/

any suggestions thx ??

<div class="wrapper">
    <div class="wrapper-item wrapper-item--0 current" data-time="2500">
        <div class="item"></div>
    </div>
    <div class="wrapper-item wrapper-item--1" data-time="5000">
        <div class="item"></div>
    </div>
    <div class="wrapper-item wrapper-item--0" data-time="7000">
        <div class="item"></div>
    </div>
    <div class="wrapper-item wrapper-item--0" data-time="9000">
        <div class="item"></div>
    </div>
</div>


function myFunction() {
    var current = $('.wrapper').children(".current") 
    var timeOfVisible = $('.wrapper').children(".current").data("time");
    setInterval(function() {
        current.removeClass("current").next().addClass("current");
        if ((current.next()) > $('.wrapper').children().length) {
            alert(current)
        }
    }, timeOfVisible);
}
myFunction()

Solution

  • First of all, you will need setTimeout instead of Interval, because you will run one delay per element. Second - you need to call your function recursively for this to repeat in a loop. Here is working js for you:

    function changeClass() {
      var current = $('.wrapper .wrapper-item.current');
      if(current.length > 0) {
         var timeOfVisible = current.data("time");
         setTimeout(function(){
        current.removeClass('current');
        if (current.next().length > 0)
            current.next().addClass('current');
        else
          $('.wrapper .wrapper-item').first().addClass('current');
          changeClass();
      }, timeOfVisible); 
      }
    };
    
    changeClass();
    

    Codepen example here.

    Also, if you don't want infinite loop, use this instead:

    function changeClass() {
      var current = $('.wrapper .wrapper-item.current');
      if(current.length > 0) {
         var timeOfVisible = current.data("time");
         setTimeout(function(){
        current.removeClass('current');
        if (current.next().length > 0) {
          current.next().addClass('current');
          changeClass(); 
        }
      }, timeOfVisible); 
      }
    };
    
    changeClass();