Ad

Stop SetInterval Timer When User Clicks On Another DOM Element

- 1 answer

Here is some example code I am working with. I need it so when the user clicks on an <li id="fade-button"> the interval stops.

var toggleSlide = function() {
  $("#slider li.uk-active")
    .removeClass()
    .next()
    .add("#slider li:first")
    .last()
    .addClass("uk-active");
}
setInterval(toggleSlide, 1000);
Ad

Answer

The setInterval method returns the id of the interval. You can store this value and use clearInterval to clear that specific interval when the element #fade-button is clicked:

Basic Example Here

var intervalId = setInterval(toggleSlide, 1000);

$('#fade-button').on('click', function () {
  clearInterval(intervalId);
});
Ad
source: stackoverflow.com
Ad