在鼠标离开时停止每个循环

Stop each loop on mouse leave

我有一个带有数据属性的锚点(一个图像对象),在 mouseenter 上我想遍历这些图像,然后在 mouseleave 上我想结束这个循环。

这是我目前所知道的,但似乎完整的 each 运行,在 shouldRotateImages 变量改变之前,即使有延迟。所以我有点不知道我现在能做什么。

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));
    });
}

通过@squint 的建议设法做到了这一点。

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);
});