Samuel Charpentier
Samuel Charpentier

Reputation: 609

How to throttle AND debounce a function?

I wondered if there's a way to throttle and debounce a function called by $( window ).resize (or any other). I've tried to only throttle but the problem is since I'm using 100% of the width of the body, if i stop resizing before the next execution of the function, the horizontal scroll apear. Therefore I need to debounce it to make shure it also execurte after the resizing is done.

If you can think of another way, please let me know!

Upvotes: 0

Views: 102

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073988

I've typically done this with setTimeout:

// Timer handle; 0 = invalid handle
var scrollTimer = 0;
$("window").on("scroll", function() {
    // Clear any pending work (it's okay to call with 0 [invalid handle], but add a guard if you like)
    clearTimeout(scrollTimer);
    // Schedule callback in X milliseconds
    setTimeout(scrollHandler, 10); // 10 = 10ms, adjust as you like
});
function scrollHandler() {
    scrollTimer = 0;
    // ...
}

If a new scroll even comes in within the interval, the previous call to scrollHandler never happens and we schedule a new one. X milliseconds after the last one, scrollHandler gets called.

Upvotes: 2

Related Questions