Search code examples
javascriptjqueryrandomflip

Auto flip randomly


I am creating an auto flipping effect on some boxes (which stop on mouse over). I have this code:

// Global flipping effect hooks
var flip_hook;
var delay;

// Flip and unflip panels
function startFlip() {
    $('div#front-page-mosaic .front-box.flip').find('div').stop().rotate3Di('flip', 500, {direction: 'clockwise', sideChange: mySideChange});
    delay = setTimeout( function() {
        $('div#front-page-mosaic .front-box.flip').find('div').stop().rotate3Di('unflip', 500, {sideChange: mySideChange});
    }, 8500);
}

// Autostart flipping effect
delay = setTimeout( function() {
    startFlip();
    flip_hook = setInterval(function(){ startFlip(); }, 17000);
}, 8000);

// Stop the flipping effect 
function stopFlip() {
    clearInterval(flip_hook);
    clearTimeout(delay);
}

// Stop flipping on mouse hover, restart on mouse leave
$('div#front-page-mosaic .front-box.flip').hover(
    function () {
        stopFlip();
    },
    function () {
        delay = setTimeout( function() {
            startFlip();
            flip_hook = setInterval(function(){ startFlip(); }, 17000);
        }, 8000);
    }
);

This works fine. But I want all boxes to flip start flipping different times, not all at the same time (although I want the flipping interval to remain the same). How can I achieve that? I tried to play with timeouts and intervals, but no luck... Any help? Thanks!


Solution

  • Try something like this in your startFlip

    var boxes= $('div#front-page-mosaic .front-box.flip').find('div');
        $.each(boxes, function(i, box){
             //(Math.random() * 10) + 1 will random a value between 1 - 10 then * 1000 to get the time in milliseconds
             var time = Math.floor((Math.random() * 10) + 1) * 1000;
             setTimeout(function(){
                   $(box).stop().rotate3Di('flip', 500);
             }, time);
         });
    

    JsFiddle example: http://jsfiddle.net/3gbksy2t/. It's not 100%, but gives you an idea of what you need to do.