点击终止一个函数

Jquery, Click to kill a function

本文关键字:一个 函数 终止      更新时间:2023-09-26

我想创建一个有三个幻灯片的滑块。最初,幻灯片将作为循环显示。我的目标是,如果点击像#fancy_1这样的按钮,函数名为"runem"的循环将被停止,循环就在那里结束。我试着放一个stop(true,true),但没有成功。不管按钮是否被点击,循环总是在运行。有人知道怎么做到这一点吗?

(function($) {
  $(document).ready(function() {
    function runem() {
      var allofEm = $('.j_fancy .j_fancy_block');
      var $active = allofEm.eq(0);
      $active.show();
      var $next = $active.next();
      var timer = setInterval(function() {
        $next.fadeIn();
        $active.hide();
        $active = $next;
        $next = (allofEm.last().index() == allofEm.index($active)) ?
          $next = allofEm.eq(0) : $active.next();
      }, 5000);
    }
    runem();
    $("#fancy_1").click(function() {
      $('.j_fancy_block').eq(0).show();
      $('.j_fancy_block').eq(1).hide();
      $('.j_fancy_block').eq(2).hide();
      runem().stop(true, true); //this doesn't work. 
    })
    $("#fancy_2").click(function() {
      $('.j_fancy_block').eq(0).hide();
      $('.j_fancy_block').eq(1).show();
      $('.j_fancy_block').eq(2).hide();
      runem().stop(true, true); //this doesn't work. 
    })

    $("#fancy_3").click(function() {
      $('.j_fancy_block').eq(0).hide();
      $('.j_fancy_block').eq(1).hide();
      $('.j_fancy_block').eq(2).show();
      runem().stop(true, true); //this doesn't work. 
    })
  })
}(jQuery));

您试过使用clearInterval()吗?stop()不工作的原因是因为这是一个停止jQuery动画的功能,而不是Javascript setInterval -所以setInterval将继续运行

我建议这样使用……

var boxInterval;
function runem(){
    /*Function Stuff*/
    boxInterval = setInterval(function(){...});
}
function stopBox(){
    clearInterval(boxInterval);
}

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval示例