问题描述
我的代码:
$(function() {
$('a.startSlideshow').click(function() {
startSlideShow = window.setInterval(function() { slideSwitch() }, 1000);
});
$('a.next').click(function() {
if (startSlideShow) {
clearInterval(startSlideShow);
}
nextSlide();
});
});
我的意图:
如果用户单击startSlideshow链接,则每1秒钟执行一次幻灯片显示功能.
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.
基本上,这导致未定义startSlideshow var时由于某些原因导致代码中断:
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?
推荐答案
在第一个处理程序之前声明startSlideShow
:
Declare startSlideShow
before your first handler:
var startSlideShow = null;
并稍后清除它:
if (startSlideShow) {
window.clearInterval(startSlideShow);
startSlideShow = null;
}
这篇关于如何在javascript中清除间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!