Home > OS >  jQuery: Delay a function from being used again once fired for a set time
jQuery: Delay a function from being used again once fired for a set time

Time:05-13

I want my function to fire on scroll, but then wait 250ms until it may fire again.

function myFunction() {
    console.log('hello');
}

$(window).on('scroll', function() {
        myFunction();
});

I have tried a timeout:

$(window).on('scroll', function() {
    setTimeout(function() {
        myFunction();
    }, 250);
});

However this method delays for 250ms before firing the function.

CodePudding user response:

Based on this answer, you can add a flag so that additional events are not fired, then clear that flag using a timeout.

Note that this will lose/drop events within the timeout, so should not be used for something like user keyboard input; where debounce would be more suitable.

var active = false;

$(window).on('scroll', function() {
    if (active) return;
    active = true;
    
    myFunction();
    setTimeout(function() {
        active = false;
    }, 250);
});

function myFunction() { console.log("scroll"); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style='height:30000px;'>
something to scroll
</div>

This is a basic throttle implementation. Improvements would be to make it modular / namespace'd and/or store the "active" flag on the element itself; so that it the same event can be reused for multiple elements and doesn't create lots of global variables.

CodePudding user response:

Simply call your function once outside of setTimeout.

$(window).on('scroll', function() {
    myFunction(); // call once

    setTimeout(function() {
        myFunction();
    }, 250); // repeat call after 250ms
});

Use setInterval instead of setTimeout if you want repeated calls every 250ms.

  • Related