1

I have an AJAX call that I only what to make if I've moused over a certain element for 2 seconds and to NOT make the call otherwise. I've tried to use setTimeout but it makes the call anyways. How can I achieve this?

Here is my code:

$('tr').mouseenter(function(){

    $( this ).next("#ticket_summary").show();
    var context = $( this ).next("#ticket_summary");
    var ticket_id = $( this ).next("#ticket_summary").data("id");
    var url = "/support/ticket_description/" + ticket_id.toString();
    console.log(url);
    setTimeout(function(){
    $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            context.find('#ticket_summary_description').html(data[1]['fields']['text']);
            context.find('#ticket_summary_last_comment').html(data[2]['fields']['text']);
        },
        error: function(data) {
            context.find('#ticket_summary_description').html('error');
            context.find('#ticket_summary_last_comment').html('error');
        }
    });
    }, 2000);
});
08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
Mmm Donuts
  • 9,551
  • 6
  • 27
  • 49

2 Answers2

3

The thing is that you have to cancel the timeout with clearTimeout if the user moves away.

Demo Fiddle

  • To detect when the user "un-hovers" use: mouseleave
  • To only handle the event once we use one
  • To cancel the timeout use: clearTimeout

The code should be something like:

$('.the-element').on('mouseenter', function (e) {
     var timeout = setTimeout(function () { ... }, 2000 );
     $(e.target).one('mouseleave', function () {
         clearTimeout(timeout)'
     });
});
Matyas
  • 13,473
  • 3
  • 60
  • 73
1

I think this will work.

HTML:

<a id='test'>LINK</a>  

JavaScript:

$("#test").mouseenter(function(){
    setTimeout(function(){
        $.ajax({
            url:"test.php",
            success:function(){
                alert("success");
            },
            error:function(){
                alert("ERROR");
            }
        });
    },5000);
});

jsFiddle:

jsFiddle

frikkievb
  • 481
  • 3
  • 11