突然停止功能,删除队列

Stop function abrupt, remove queue

所以,我有一个必须使图标具有动画效果的函数:

https://jsfiddle.net/1658eaLr/

我想要的是,当鼠标离开元素 .button8 时,函数会突然停止并移除队列。

问题是,当我用鼠标快速进出时,动画搞砸了。

我也试过用graph().stop();,但也没用

类似于您已经在使用的 clearInterval 方法,setTimeout 将 return 一个唯一的 timeoutId,您可以使用它来取消所有使用 window.clearTimeout.

的未决超时

因此,保持大部分代码不变,您可以编写

var interval, timeout;
var graph = function(){
$('.graph-line1').addClass('graph-line1-animate');
timeout = setTimeout(function(e){
    $('.graph-line2').addClass('graph-line2-animate');
    timeout = setTimeout(function(e){
        $('.graph-line3').addClass('graph-line3-animate');
         //... rest of the timeouts

然后在"hover out"回调

clearInterval(interval);
clearTimeout(timeout);

Here's a working fiddle.

顺便说一句,这些嵌套超时可以写得更干净一点以避免 "callback hell"。 Here's my quick attempt,但我敢打赌你可以做得更好。

在上述答案的基础上,您还可以通过删除整个 interval = 回调集并按如下方式更改底部来去掉一半代码:

$(document).ready(function(e){
  $('.button8').hover(function(e){
  graph();
  interval = setInterval(graph, 2000);
}, function(e){
  clearInterval(interval);
  clearTimeout(timeout);
});