user2946632
user2946632

Reputation: 111

How to reduce the number of triggered mousewheel scroll events in a time interval to a single event

Currently in my site, I have a mousewheel function that scrolls the user to set positions on the page. This function, however, triggers multiple times when users scroll somewhat quickly and don't limit their scrolling to a single unit of mousewheel scroll. How do I take all the mousewheel scroll events in a certain time interval of lets say one second and make that trigger my function a single time?

Upvotes: 3

Views: 1872

Answers (2)

user5174817
user5174817

Reputation:

This jQuery code lets you set an interval in milliseconds.

var intervalMs = 2000;

var last = 0;
$(document).scroll(function() {
  var now = new Date().getTime();
  if (last + intervalMs < now) {
    last = now;
    
    // do stuff
  }
});

Upvotes: 0

Alex McMillan
Alex McMillan

Reputation: 17952

You could use debouncing on your event handler. Underscore / lodash provide debounce functionality, but jQuery does not. A simple example taken from here looks like this:

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);
    };
};

Once you have this available, you can use it like this:

var delay = 1000; // 1s

var handlerFunction = debounce(function (e) {
  console.log(1);
}, delay);

$(document).on('scroll', handlerFunction);

And your handler will only actually execute 1000ms after the last time the handler is called.

JSBIN here for you to play with.

Upvotes: 4

Related Questions