Reputation: 5463
I have an anchor with a data attribute (an object of images), on mouseenter I want to loop through these images, then on mouseleave I want this loop to end.
Here's what I have so far, but it seems the full each
runs, prior to the shouldRotateImages
variable changing, even with the delay. So I'm a bit lost as to what I can do now.
var shouldRotateThumbnails = false;
$(document).on('mouseenter', '#videos-list a', function () {
shouldRotateThumbnails = true;
rotateThumbnails($(this));
});
$(document).on('mouseleave', '#videos-list a', function () {
shouldRotateThumbnails = false;
});
function rotateThumbnails(video) {
var thumbnails = video.data('thumbnails');
var image = video.find('img');
$.each(thumbnails, function (k, v) {
if (!shouldRotateThumbnails) {
return false;
}
setTimeout(function () {
image.attr('src', v);
}, (300 * k));
});
}
Upvotes: 0
Views: 95
Reputation: 5463
Managed to do this by using @squint's suggestion.
var t;
$(document).on('mouseenter', '#videos-list a', function () {
var imageKey = 0;
var thumbnails = $(this).data('thumbnails');
var image = $(this).find('img');
t = setInterval(function () {
image.attr('src', thumbnails[imageKey]);
imageKey += 1;
if (imageKey == thumbnails.length) {
imageKey = 0;
}
}, 300);
});
$(document).on('mouseleave', '#videos-list a', function () {
clearInterval(t);
var image = $(this).find('img');
var thumbnail = $(this).data('original-thumbnail');
image.attr('src', thumbnail);
});
Upvotes: 3