Similar to the debounce/throttle functions found in Lodash, but meant to be be run within the function itself instead of attached to an event. This keeps your code clean (no need to attach debounce to EVERY event trigger) and ensures that your functions are consistently throttled no matter how many triggers there might be.
To use these functions, simply place them at the top of your function like so and they will limit how often the rest of your function is run based on the settings:
function exampleFunction() {
if(debounce()) return;
// Continue running function...
}
or
if(throttle()) return;
This library comes with two functions to control your functions:
Prevent function from running until wait number of milliseconds has passed without it being triggered.
Prevent function more than once every wait milliseconds.
The debounce() and throttle() functions will make smart assumptions about how to run if no arguments are given, but can be configured to run
The number of milliseconds to delay. Default: 100
Control when the function will run in relation to the timeout.
{
leading: false,
trailing: true,
maxWait: true,
function: '',
arguments: [],
}
Set to true if you want function to run on leading edge of timeout Default: false
Set to true if you want function to run on trailing edge of timeout Default: false
The maximum time (in ms) function is allowed to be delayed before it's invoked Default: 0
The name of the function to run. If blank, it will use the name of the function that called it.
Note: The function name is derived from the arguments.callee object, which isn't supported on older browsers. If you need to support legacy browsers, use this setting.
A list of arguments to be passed to function call. If blank, it will use the arguments of the function that called it.
Note: Also uses arguments.callee. See previous note about supporting older browsers.
The function will only run after the mouse has stopped moving for at least 500ms:
function example1() {
if(debounce(500)) return;
// Continue running function...
}
$('.demo1').mousemove(example1);
Mouse event triggered 0 times
Function run 0 times
Function Run!
The function will run every 1000ms as long as the box registers a mouse movement:
function example2() {
if(throttle(1000)) return;
// Continue running function...
}
$('.demo2').mousemove(example2);
Mouse event triggered 0 times
Function run 0 times
Function Run!
Arguments will be passed along with the function call each time it's triggered.
The function will run once but not again until after 100ms of no mouse movement:
function example3(_string, _number, _null) {
if(debounce({
function: 'example3',
arguments: [_string, _number, _null],
leading: true,
trailing: false,
maxWait: false
})) return;
// Continue running function...
}
$('.demo3').mousemove(function() {
example3('test', 34, null);
});
Mouse event triggered 0 times
Arguments:
Function run 0 times
Function Run!