admin管理员组

文章数量:1277380

I have a jQuery/JS function that is using setInterval to loop through some image slides I have. It just flips through every 5 seconds...

Now I want it to pause if my mouse is hovered over it. How do I go about doing that on the setInterval function?

var current = 1;

function autoAdvance() {
    if (current == -1) return false;

    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}

// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);

I have a jQuery/JS function that is using setInterval to loop through some image slides I have. It just flips through every 5 seconds...

Now I want it to pause if my mouse is hovered over it. How do I go about doing that on the setInterval function?

var current = 1;

function autoAdvance() {
    if (current == -1) return false;

    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}

// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);
Share Improve this question edited Mar 25, 2013 at 14:29 Danny Beckett 20.8k25 gold badges112 silver badges142 bronze badges asked Jan 22, 2011 at 4:25 user381800user381800
Add a ment  | 

2 Answers 2

Reset to default 4

Something like this would work assuming interval is defined in an outer scope:

$('.slideshow img').hover(function() {
  interval = clearInterval(interval);
}, function() {
  interval = setInterval(flip, 5000);
});
(function () {
    var imgs = $('#your_div img'), index = 0, interval,

        interval_function = function () {
            imgs.eq(index).hide();
            index = (index + 1) % imgs.length;
            imgs.eq(index).show();
        };

    imgs.eq(0).show();
    interval = setInterval(interval_function, 5000);

    $('#your_div').hover(function () {
        clearInterval(interval);
    }, function () {
        interval = setInterval(interval_function, 5000);
    });
}());

Example: http://jsfiddle/Zq7KB/3/

I reused some old code I wrote for a question the other day, but I figured it didn't matter that much. The trick is to store your interval in a variable that you keep in the background. Then, when you hover over the container, clear the interval. When you hover out of the container, re-set the interval. To get a better feel of how this works, change those 5000s to 1000s so it passes more quickly for testing.

Hope this helps.

本文标签: javascriptjQuery pause function on hoverStack Overflow