Reputation:
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 }
});
});
Upvotes: 2
Views: 300
Reputation: 28611
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/
Upvotes: 2