Search code examples
jqueryhoverdelaysettimeoutwait

Prevent Multiple Firing of Script on Scroll


I've got a list of spans, with 'meta-data' stored in the alt tag. When the user hovers over the span, for a full second, the alt tag information is appended to a different element, to be read.

My issue, is that if I quickly scroll across a number of spans, the script fires multiple times; so setTimeout() is pointless, since they all fire eventually and I get all of those alts appended, versus just the one that was hovered on for the full second.

var target;
$("#LIST span").live('hover', function(){
    target = $(this);
    setTimeout(function() {
        getALT = target.attr('alt');
        $(document).showALT();
    }, 1000);
});

jQuery.fn.showALT = function(){
    $("#tell2").append('X ')
    $(".Show_Info").attr('src', getALT);
}

The above is clearly flawed, and I know why, as stated above. I'm not sure how to accomplish what I want.


Solution

  • Clear it before use.

    var target;
    var timeO;
    $("#LIST span").live('hover', function(){
        target = $(this);
        clearTimeout(timeO);
        timeO = setTimeout(function() {
            getALT = target.attr('alt');
            $(document).showALT();
        }, 1000);
    });
    
    jQuery.fn.showALT = function(){
        $("#tell2").append('X ')
        $(".Show_Info").attr('src', getALT);
    }
    

    P.S: you can use also: function showALT(){ instead of: jQuery.fn.showALT = function(){

    PS2: if you use jQ 7+ than .live() method is deprecated. Use .on() instead like:

    $("#LIST").on('hover','span', function(){