0

尝试构建一个允许用户单击播放的图表,它将在一系列年份中循环,在图表中显示每一年几秒钟,然后再进入下一个。
它还应该允许用户点击暂停,暂停动画;这是我失败的地方。

我相当确定我的问题是范围界定,但不是 100%;我已经将它带到动画将循环播放的位置,但是当用户单击暂停时,它会继续循环播放,而不是将动画暂停。我可以看到clearInterval正在启动console.log,但同样,它什么也不做,动画继续。

setTimeout用来延迟每个图表的出现并使用(肯定是以错误的方式)setInterval来安排循环。我在这里阅读/尝试了许多处理setTimeoutand的答案setInterval,但无济于事。我很肯定,这是我不理解为什么它们不起作用,而不是我的问题与其他问题“不同”。

也就是说,我已经在桌子上敲了三天的头,真的可以在这里使用一些指针。下面是我目前正在使用的 JavaScript/jQuery:

jQuery('#animation-play').on('click', function() {
  // loopThroughYears();
  var animation;
  if (jQuery('#animation-play').hasClass('play')) {
    jQuery('#animation-play').addClass('stop').removeClass('play').text('Pause Animation');
    var years = [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015];
    var time = 1000;
    if (animation) {
      clearInterval(animation);
    }
    animation = setInterval(function() {
      $.each(years, function(index, values) {
        setTimeout(function() {
          if (years.this < 2016) {
            selectChartYear(values);
            jQuery("#chart-years").val(values);
          }
        }, time);
      });
    }, time);
  } else {
    jQuery('#animation-play').addClass('play').removeClass('stop').text('Play Animation');
    console.log("Timeout Cleared!");
    clearInterval(animation);
  }
});
4

1 回答 1

4

animation变量在点击处理程序中声明,每次点击时都会创建一个新变量。

您必须将该变量存储在其他地方,例如使用 jQuery 的元素data()

jQuery('#animation-play').on('click', function() {
    
    clearInterval( $(this).data('animation') );
    
    if (jQuery('#animation-play').hasClass('play')) {
        jQuery('#animation-play').addClass('stop')
                                 .removeClass('play')
                                 .text('Pause Animation');
                                 
        var years = [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015];
        var time  = 1000;
        var self  = $(this);
        
        self.data('year', self.data('year') || -1);
        
        self.data('animation', 
            setInterval(function() {
            	var idx   = self.data('year') + 1;
                if ( idx > years.length ) {
                	idx = 0;
                    self.trigger('click');
                } else {
                    var value = years[idx];

                    //selectChartYear(value);
                    jQuery("#chart-years").val(value);
                }
                
				self.data('year', idx);
            }, time)
        );
    } else {
        jQuery('#animation-play').addClass('play')
        						 .removeClass('stop')
                                 .text('Play Animation');
                                 
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="animation-play" class="play">
    click here to start
</div>
<br/>
<input id="chart-years" />

于 2017-04-20T20:29:45.753 回答