Run function after some time

Asked

Viewed 16,413 times

5

Hello, I have the following code (just studying):

$('#test').hover(function(){
        $('.box-one, .box-two, .box-three').hide();
        $(this).removeClass('test').addClass('another-test').stop().animate({'height':'210px'});
        $('.my-message').fadeIn();

}, function(){
        $('.box-one, .box-two, .box-three').fadeIn();
        $(this).removeClass('another-test').stop().animate({'height':'110px'}).addClass('test');
        $('.my-message').fadeOut();
});

When hovering the mouse over the element, I should expect something around 0,400 seconds until the function activates, but if I give up or simply passed the mouse by mistake, the function must recognize that the mouse is no longer on top of the element and with this must cancel what would be done...

3 answers

9


Hmm interesting, here’s an idea that uses the setTimeout to trigger the animation after 400ms of the Hover. In case the mouse leaves, then the code clears the setTimeout and the code within the function is ignored.

var pairar;
$('#test').hover(function () {
    pairar = setTimeout(function (self) { 
      // usei a variavel "self" como parametro,                                   
      //  e que representa o "this" fora da funcao setInterval
        $('.box-one, .box-two, .box-three').hide();
        $(self).removeClass('test').addClass('another-test').stop().animate({ 
            'height': '210px'
        });
        $('.my-message').fadeIn();
    }, 400, this); // repara que passei o "this" como parametro aqui para o seletor funcionar. 
                   // Chamei-lhe "self" dentro da funcao mas podes usar outro nome
}, function () {
    clearTimeout(pairar);
    $('.box-one, .box-two, .box-three').fadeIn();
    $(this).removeClass('another-test').stop().animate({
        'height': '110px'
    }).addClass('test');
    $('.my-message').fadeOut();
});

jsFiddle

  • 2

    The passage of own to "within" the timer is in fact something critical in these implementations +1 I didn’t remember that!

  • I believe that this answer has two problems. One would be the use of setInterval, that defines a timer that runs several times, not just once. Another problem occurs that the output action will always occur when the cursor is removed from above the element #test, even before 400 ms.

6

If all you want is to wait an X of time before actually running the code associated with hover, one timer resolve your issue:

var tempo_espera;
$('#test').hover(
    function() {
        tempo_espera = setTimeout(function() { 
            // o teu código mouse hover aqui
        }, 400);
    },
    function() {
        clearTimeout(tempo_espera);
        // o teu código mouse out
    }
);

What we’re doing is creating a envelope whenever the mouse hovers over the widget, so that your code is only executed after the specified time.

When the mouse leaves the element, we’re clearing the waiting time.

  • 1

    Your answer has a better explanation than mine :p +1

5

I recommend using the plugin hoverIntent.

However, it is not something difficult to implement in pure Javascript, with the use of window.setTimeout(callback, millisecs).

var hoverIn = function () { ... }; // callback para o que fazer quando o
                                   // cursor entra no elemento #test

var hoverOut = function () { ... }; // callback para o que fazer quando o
                                    // cursor sai do elemento #test
var timeout; // referência do timer

$('#test').hover(function () {
    // ao entrar no elemento #test, o timer será ajustado

    timeout = setTimeout(function () { // quando o timer for disparado...
       timeout = false; // ... apagamos sua referência ...
       hoverIn(); // e executamos o callback de entrada
    }, 400);

}, function () {
    // ao sair do elemento #test ...

    if ( timeout )
       clearTimeout(timeout); // Se ainda houver referência ao timer,
                              // nós o desativamos
    else
       hoverOut(); // Caso contrário, nós executamos o callback de saída,
                   // pois hoverIn() já foi executado. 
});
  • Control when mouse is exiting element is excellent! + 1 Checking whether or not to run associated code :)

  • Good explanation, +1

  • Great answer. I was going to write something but here explains everything.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.