liborza
liborza

Reputation: 1009

Function is broke after few loops

I try to figured out the problem why my function is broken after few loops..

When i run my webpage its working fine but when i open another tab in my browser and let the function running and let it do for few loops and then back to that webpage the function is few times refreshing and after den the fadeout for background color start blinking but it be set up for 2000ms.. Any ideas for fix that ?

I try to do this : clear interval and run function again after every loop but it do same thing..

Here is a sample : enter link here

$(document).ready(function () {
  var mixit = $('#Container').mixItUp({
    load: {
      sort: 'random'
    },
    layout: {
      containerClass: 'list',
      display: 'block'
    }
  });

  function loop() {
    var arr = [];
    i = 0;
    $('.mix').each(function(){
      arr[i++] = $(this).data('myorder');
    });
    mixit.mixItUp('sort', 'random');

    mixit.on('mixEnd', function(e, state){
      var arr2 = [];
    i2 = 0;
    $('.mix').each(function(){
      arr2[i2++] = $(this).data('myorder');
    });
    for(i=0; i<i2; i++){
      for(j=0; j<i2; j++){
        if(arr[i]==arr2[j]){
          if(i<j){
            $('.mix').eq(j).css("background-color", "white");
          }
          if(i>j){
            $('.mix').eq(j).bgColorFade({
    time: 2000
});
          }
        }
      }
    }
    });
  };

  var looper = setInterval(loop, 5000);
});

$.fn.bgColorFade = function(mixcolor) {
    // starting color, ending color, duration in ms
    var options = $.extend({
      start: 'green',
        end: 'white',
      time: 2000
    }, mixcolor || {});
    $(this).css({
        backgroundColor: options.start
    }).animate({
        backgroundColor: options.end
    }, options.time);
    return this;
};

Upvotes: 0

Views: 127

Answers (1)

Orest Hera
Orest Hera

Reputation: 6776

There is animation option queue (default: true) indicating whether to place the animation in the effects queue. To start animation immediately it should be set to false. The timers are not perfect (especially during switching tabs). Here the effects queue is not needed for color animation. It should start immediately. Disabling the queue (queue: false) fixes the animation:

$(this).css({
    backgroundColor: options.start
}).animate({
    backgroundColor: options.end
}, {
    duration: options.time,
    queue: false
});

The main reason for the broken animation is progressive registration of the mixEnd event handlers. The function mixit.on('mixEnd', function(e, state){...}) should not be called inside the loop function, since during each call it registers a new handler function. So, the number of the even handler calls grows progressively with time. That was causing large queue for the animation effects.

So, if the callback is registered only once there is no problems: http://jsfiddle.net/1unLu3d4/3/

Upvotes: 2

Related Questions