Cleartimeout多个settimeout

时间:2013-12-03 08:53:28

标签: javascript jquery settimeout

如果我有多个settimeout,我怎么能做clearTimeout? 我在这里有一个代码:

var $elie = $(".gear"), degree = 0, timer;


function rotate() {

    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});  
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});                      
    $elie.css({ 'transform': 'rotate(' + degree + 'deg)'});                      
    timer = setTimeout(function() {
        ++degree; rotate();
        $('.gear').attr('timeout',timer);
    },25);
}

$(".google").hover(function() {

    clearTimeout($('.gear').attr('timeout'));


});
$(".gear").hover(function() {
    rotate();
});

即:http://jsfiddle.net/T9YxL/1/ 问题是:我将鼠标悬停在齿轮上一次,而不是悬停在Google徽标上 - 一切都停止了。但是当我两次悬停在齿轮上时,我必须在Google徽标上悬停两次,依此类推。如何立即清除所有这些设定时间,甚至例如我在齿轮上徘徊100次?

我看了看这里: clearTimeout on multiple setTimeout 但它没有帮助。

1 个答案:

答案 0 :(得分:0)

timer = setTimeout(function() {
    ++degree; rotate();
    $('.gear').attr('timeout',timer);
},25);

应该是

timer = setTimeout(function() {
    ++degree; rotate();
},25);
$('.gear').attr('timeout',timer);

和:

$(".gear").hover(function() {
    rotate();
});

应该是

$(".gear").hover(function() {
    clearTimeout($('.gear').attr('timeout'));
    rotate();
});

fiddle