user2356198 user2356198 - 3 months ago 5
Javascript Question

How to prevent multiple fires for scroll event?

I try to prevent multi times scroll event, e.g. only one event in 250ms. For this I found the debounce function below in Internet. But I couldn't use it properly. What is wrong?

function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};

// my code..
$(window).on('scroll', function (e) {

debounce(function() {
// The stuff below doesn't work.
var scrollTop = $(window).scrollTop();
if (scrollTop > 50) {
$('.title').addClass('fixedPosition');
} else {
$('.title').removeClass('fixedPosition');
}
}, 250);

});

Answer

Since the function debounce returns a function, you still need to call it:

$(window).on('scroll', function (e) {
    debounce(function() {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > 50) {
            $('.title').addClass('fixedPosition');
        } else {
            $('.title').removeClass('fixedPosition');
        }    
    }()/*note the call here*/, 250);
});

This is not the same as wrapping your debounce logic in another function whereas the function myLogic will be called automatically:

function myLogic(){
    var scrollTop = $(window).scrollTop();
    $('.title').toggleClass('fixedPosition', scrollTop > 50);
}

$(window).on('scroll', debounce(myLogic, 250));
Comments