Pregunta

I'm having an issue when using the SetTimeout function.

I have a box and when you hover it, it turns blue. If you then leave it, it will turn back to red with a delay of 1 second.

The problem is however, that if hover the box, leave it and then quickly hovers it again before the 1 second, it will turn blue for a little while, and then back to red.

The idea behind it is, that it should stay blue and only turn back to red if the you leave the box in more than 1 second. Hope you understand me :)

Why is this happening?

I have really no idea why.


Heres my jQuery code:

$('.box').hover(function() {
    $('.box').css({'background' : 'blue'});
}, function() {
    setTimeout(test, 1000);
    function test() {
        $('.box').css({'background' : 'red'});
    }
});

I've tried to do a google search and found these: $(".box").stop(true,true).delay(1000).css({'background' : 'red'}); and:

$('.box').hover(function() {
    $('.box').css({'background' : 'blue'});
}, function() {
    $('.box').delay(1000).queue( function(next){ 
        $('.box').css({'background' : 'red'});
        next(); 
    });
});

But none seems to work properly.

Can someone please help me :)?

Thanks - TheYaXxE

Fiddle Example

¿Fue útil?

Solución

You'll have to store the timer so it can be cleared when hovering again

$('.box').on({
    mouseenter: function() {
        $(this).css('background', 'blue');
        clearTimeout($(this).data('timer'));
    },
    mouseleave: function() {
        var self = this;
        $(this).data('timer', 
            setTimeout(function() {
                $(self).css('background', 'red');
            }, 1000)
        );
    }
});

FIDDLE

Otros consejos

Using delay and in/out hover handler, you could use:

DEMO jsFiddle

$('.box').hover(function (e) {
    var delay = e.originalEvent.type === "mouseover" ? 0 : 1000;
    $(this).finish().delay(delay).queue(function () {
        $(this).css({
            'background': e.originalEvent.type === "mouseover" ? 'blue' : 'red'
        });
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top