Search code examples
javascriptjqueryhtmljquery-effects

How to Prevent Queue Build-up jQuery


I am trying to make a navigation bar appear only when the mouse is moving or the window is scrolling. It should appear for 3 seconds and then disappear. This works, but for each pixel that my mouse or window moves, it adds the function to fade in and then out again to the queue, and with the jQuery animation delay, it does this over and over again essentially making the navigation blink for 3 seconds forever. Is there a way to use the .clearQueue() method to prevent this from happening, or is there another more efficient way of doing this?

html:

<div id="gallery"></div>

<div id="control">

    <div id="previous-button" class="button"></div>
    <div id="next-button" class="button"></div>

</div>

jQuery:

    t = 300;

    function cBar() {
        $("#control").fadeIn(t);
        $("#control").delay(t*10).fadeOut(t);
    }

    $(window).scroll(function() {
        console.log("scroll");
        cBar();
    });
    $(window).mousemove(function() {
        console.log("mouse");
        cBar();
    });

Solution

  • Use the setTimeout() function with a variable that store the timer:

    t = 300;
    var timer;
    
    function cBar() {
        if( timer ){
            clearTimeout(timer);
        }
        $("#control").fadeIn(t);
    
        timer = setTimeout(function(){
            $("#control").fadeOut(t);
            timer = null;
        }, t*10);
    }
    
    $(window).scroll(function() {
        console.log("scroll");
        cBar();
    });
    $(window).mousemove(function() {
        console.log("mouse");
        cBar();
    });