I’m looking for a simple & semantic way to code jQuery event handlers that allow a reasonable timeout or other way of ‘slowing’ down the rate at which events are fired, in order to prevent the user from spamming (on purpose or inadvertantly) my handlers.
This isn’t usually a concern for me personally as in most cases simply halting the operations of the previous handler is enough – example being a fading menu; simply using .stop() on the animations is good enough.
However I’m now building a much more js heavy page whose events are simply too expensive to fire off more than once or twice a second, and with multiple ways of firing those events I find myself needing to limit how often they will execute at a more base level.
An example of the problem:
$(document).bind('mousewheel', function(e, delta){
alert('you scrolled the mousewheel!');
stopLoadsOfStuff();
fadeHalfADozenImagesInAndOutAgain();
});
I’m using the mousewheel plugin (here: http://brandonaaron.net/code/mousewheel/docs) as depending on mouse, OS or manufacturer supplied software, the scroll rate can vary wildly. Think one of those shiny apple touch mice vs an old ball mouse from the 90s. If you fire an event on scroll, you will find that you need to limit it to something sensible unless your event is very cheap to execute and stop.
Things I’ve already tried are:
For clicks and keyboard events:
setting a boolean for each event, setting it to true while the event fires and using a callback to set it to false again. Event only executes if bool is false.
This worked, but is messy and a little too specific.
For mousewheel events:
I increment an integer variable each time a mousewheel event is detected, and only take action if it’s more than 5. The handler resets it to 0 on execution.
tl;dr
I need an extendable, simple way to limit the rate of execution of event handlers which will allow me to use expensive event handlers without worrying about the user attempting to execute them 100 times a second 🙂
Any help appreciated
You may be interested in the jQuery debounce plugin.
The concept behind the plugin is that it wraps the handler you pass in another function, which rate limits the execution of the function by only calling it every
xmilliseconds.