简体   繁体   中英

Stop setInterval timer when user clicks on another DOM Element

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM