JQuery pause function when freezing?

I have a jQuery / JS function that uses setInterval to scroll through some of the image slides that I have. It just scans every 5 seconds ...

Now I want him to stop if my mouse hangs over him. How can I do this using 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); 
+4
source share
2 answers

Something like this will work if interval is defined in the outer scope:

 $('.slideshow img').hover(function() { interval = clearInterval(interval); }, function() { interval = setInterval(flip, 5000); }); 
+4
source
 (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.net/Zq7KB/3/

I again used the old code that I wrote to the question the other day, but I thought it was not so important. The trick is to keep your interval in a variable that you save in the background. Then, when you hover over the container, clear the interval. When you exit the container, reset the interval. To better understand how this works, change those 5000 to 1000 so that it passes the test faster.

Hope this helps.

+3
source

Source: https://habr.com/ru/post/1336546/


All Articles