jQuery! I fail to use _.debounce properly

298 views Asked by At

I'm trying to use the function _.debounce() of underscore.js but I can't do it properly.

I'm trying to debounce the scroll of my window as shown below, but I am seriously confused.

$(document).ready(function () {
 $(window).scroll(function (event) {
    var scrollCounter = $(this).scrollTop();
    if ( scrollCounter > 0 ) { //do stuff }
    else { //do stuff }
 });
});
1

There are 1 answers

5
fdomn-m On BEST ANSWER

From the documentation and example:

var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);

you can refactor your call to debounce it like this:

function scrollHandler() {
    var scrollCounter = $(this).scrollTop();
    if ( scrollCounter > 0 ) { /* do stuff /* }
    else { /* do stuff */ }
};

$(document).ready(function () {

    var debouncedScroll = _.debounce(scrollHandler, 50);
    $(window).scroll(debouncedScroll);

});

Update: Working jsfilddle: https://jsfiddle.net/z635f7ys/