How to do a clear interval in javascript?
My Code:
$(function() {
$('a.startSlideshow').click(function() {
startSlideShow = window.setInterval(function() { slideSw开发者_运维知识库itch() }, 1000);
});
$('a.next').click(function() {
if (startSlideShow) {
clearInterval(startSlideShow);
}
nextSlide();
});
});
My Intention:
If a user clicks the startSlideshow link the slideshow function is executed every 1 seconds.
If the user clicks the next link, the slideshow function is stopped IF IT HAS ALREADY BEEN EXECUTED.
To be able to detect this, I stored the set interval as a variable. However when I check for it:
if (startSlideShow) {
clearInterval(startSlideShow);
}
It doesn't work. Right now my code works if I click on the start slideshow link before clicking next. But if the slideshow function was never started (i.e. I never clicked that link first but clicked next from the start) the code fails.
basically this is causing the code to break for some reason when startSlideshow var hasn't been defined:
if (startSlideShow) {
clearInterval(startSlideShow);
}
I did try other ways of checking to see if that variable has been set, but all failed. How to solve this?
Declare startSlideShow
before your first handler:
var startSlideShow = null;
And clear it later:
if (startSlideShow) {
window.clearInterval(startSlideShow);
startSlideShow = null;
}
I believe you have a scope issue:
$(function() {
var startSlideShow;
$('a.startSlideshow').click(function() {
startSlideShow = window.setInterval(function() { slideSwitch() }, 1000);
});
$('a.next').click(function() {
if (startSlideShow) {
clearInterval(startSlideShow);
}
nextSlide();
});
});
Define the variable outside of the click functions.
That is because you do no declare startSlideShow, so it doesn't exist until the start function is run. At that point, it becomes a global variable with a value.
You should include it in a closure and declare it with var.
精彩评论