简体   繁体   English

如何在 javascript 中做一个明确的区间?

[英]How to do a clear interval in javascript?

My Code:我的代码:

$(function() {

     $('a.startSlideshow').click(function() {     
          startSlideShow = window.setInterval(function() { slideSwitch() }, 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.如果用户单击 startSlideshow 链接,则幻灯片 function 每 1 秒执行一次。

If the user clicks the next link, the slideshow function is stopped IF IT HAS ALREADY BEEN EXECUTED.如果用户单击下一个链接,如果幻灯片 function 已经执行,则会停止。

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 (ie I never clicked that link first but clicked next from the start) the code fails.但是,如果幻灯片 function 从未启动(即我从未先单击该链接,而是从头开始单击下一步),则代码将失败。

basically this is causing the code to break for some reason when startSlideshow var hasn't been defined:基本上,当尚未定义 startSlideshow var 时,这会导致代码因某种原因中断:

      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?如何解决这个问题?

I believe you have a scope issue:我相信你有一个 scope 问题:

$(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.在点击函数之外定义变量。

Declare startSlideShow before your first handler:在您的第一个处理程序之前声明startSlideShow

var startSlideShow = null;

And clear it later:稍后清除:

if (startSlideShow) {
    window.clearInterval(startSlideShow);
    startSlideShow = null;
} 

That is because you do no declare startSlideShow , so it doesn't exist until the start function is run.那是因为你没有声明startSlideShow ,所以它在 start function 运行之前不存在。 At that point, it becomes a global variable with a value.到那时,它就变成了一个有值的全局变量。

You should include it in a closure and declare it with var .您应该将其包含在闭包中并使用var声明它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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