【问题标题】:Trying to understand how to use clearInterval with JS [duplicate]试图了解如何在 JS 中使用 clearInterval [重复]
【发布时间】:2017-08-18 00:57:26
【问题描述】:

我正在使用 JavaScript 并尝试编写一个函数来使颜色闪烁,但问题是当我单击切换闪烁按钮时,当我单击停止切换结束按钮时它不会停止闪烁。我正在尝试实施 clearInterval 以使其停止但没有运气。任何帮助表示赞赏。

function main() {
  $('.select-color').on('click', function() {
    var selectedColor = $(this).attr('class');

    switch (selectedColor) {
  case 'select-color cyan not-selected':
    colorClass = 'cyan';
    break;
  case 'select-color yellow not-selected':
    colorClass = 'yellow';
    break;
  case 'select-color magenta not-selected':
    colorClass = 'magenta';
    break;
    }
    $(this).removeClass('not-selected');
    $(this).siblings().addClass('not-selected');
  });

  var colorClass = '';


  $('.box').on('click', function() {
        $(this).toggleClass(colorClass);
    });

  $('.toggle-blink').on('click', function() {
    if (colorClass) {
        $('.toggle-blink').toggleClass('opacity');
    }
    setInterval(function() {
          $('.box.cyan, .box.yellow, .box.magenta').toggleClass('blink');      
                }, 500); 
    });

  $('.toggle-blink-end').on('click', function() {
   scope.clearInterval(main);
  });

}

$(document).ready(main);

【问题讨论】:

  • clearInterval 用于停止 setInterval 对传递给它的函数的循环调用

标签: javascript clearinterval


【解决方案1】:

clearInterval() 将 intervalID 作为参数,而不是函数引用,因此在调用返回给定 intervalID 的 setInterval() 时需要存储它:

var intervalID ;

intervalID = setInterval( ... );

clearInterval(intervalID);

【讨论】:

    【解决方案2】:

    为了使用clearInterval,您需要将setInterval 的结果存储在一个变量中:

    const pid = setInterval(
      /*some func*/,
      /*some duration in ms*/
    );
    
    //later on (same scope as pid) 
    
    clearInterval(pid);
    

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      相关资源
      最近更新 更多