Stop function abrupt, remove queue

时间:2016-04-25 09:19:23

标签: javascript jquery function setinterval

So, I have a function that has to animate an icon:

https://jsfiddle.net/1658eaLr/

What I want, is when the mouse leaves the element .button8, that the function will stop abruptly and remove the queue.

The problem is, is when I go in and out very fast with the mouse, the animation messes up.

I also tried to use graph().stop();, but that didn't work either

2 个答案:

答案 0 :(得分:1)

Similarly to the clearInterval method you are already using, setTimeout will return a unique timeoutId which you can use to cancel all the pending timeouts using window.clearTimeout.

So, keeping most of your code untouched, you could write

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

And then in the "hover out" callback

clearInterval(interval);
clearTimeout(timeout);

Here's a working fiddle.

As an aside, these nested timeouts could be written a bit more cleanly to avoid the "callback hell". Here's my quick attempt, but I bet you could do even better.

答案 1 :(得分:1)

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

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