randomFlipping = function(){ // So we know what to flip var mediaItem = $('.xItem.xMedialayer.xContentImage, .xItem.xMedialayer.xContentVideo'); // So we know how many items there are var totalItemsWithMedia = $(mediaItem).length; // Want to run the function on a somewhat random interval setInterval(function(){ // Randomly finding an element to flip var itemNumberToFlip = Math.round(Math.random() * totalItemsWithMedia); var itemToFlip = $(mediaItem)[itemNumberToFlip]; // Flip the element $(itemToFlip).find('.xItemInner').addClass('xActive'); // Flip the element back in a few seconds setTimeout(function(){ $(itemToFlip).find('.xItemInner').removeClass('xActive'); }, (Math.random() * 6) + 6 * 1000); }, ((Math.random() * 6)) * 500); },