Skip to content Skip to sidebar Skip to footer

Eventhandler Is Disabled For Longer Than Expected

I'm making a simple full viewport scroller. You can change sections by triggering wheel event. To prevent the eventhandler from firing many times in row and skipping pages, I've

Solution 1:

It seems like what you want is a debounce function. I'd recommend using this one, by David Walsh:

functiondebounce(func, wait, immediate) {
    var timeout;
    returnfunction() {
        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);
    };
};

Usage

var myScrollFunction = debounce(function() {
    // All the taxing stuff you do
}, 250);

document.addEventListener('wheel', myScrollFunction);

To answer why your code doesn't work as expected: The mouse wheel produces a series of continuous events while it is scrolling, so your time diff is constantly < 200. Here's an example of it working "properly" (though the best answer is still a true debounce function as stated above).

JSBin examplehttps://jsbin.com/cuqacideto/edit?html,console,output

Post a Comment for "Eventhandler Is Disabled For Longer Than Expected"