You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.8 KiB
56 lines
1.8 KiB
3 years ago
|
/**
|
||
|
* debounce
|
||
|
* @param {integer} milliseconds This param indicates the number of milliseconds
|
||
|
* to wait after the last call before calling the original function.
|
||
|
* @param {object} What "this" refers to in the returned function.
|
||
|
* @return {function} This returns a function that when called will wait the
|
||
|
* indicated number of milliseconds after the last call before
|
||
|
* calling the original function.
|
||
|
*/
|
||
|
Function.prototype.debounce = function (milliseconds, context) {
|
||
|
var baseFunction = this,
|
||
|
timer = null,
|
||
|
wait = milliseconds;
|
||
|
|
||
|
return function () {
|
||
|
var self = context || this,
|
||
|
args = arguments;
|
||
|
|
||
|
function complete() {
|
||
|
baseFunction.apply(self, args);
|
||
|
timer = null;
|
||
|
}
|
||
|
|
||
|
if (timer) {
|
||
|
clearTimeout(timer);
|
||
|
}
|
||
|
|
||
|
timer = setTimeout(complete, wait);
|
||
|
};
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* throttle
|
||
|
* @param {integer} milliseconds This param indicates the number of milliseconds
|
||
|
* to wait between calls before calling the original function.
|
||
|
* @param {object} What "this" refers to in the returned function.
|
||
|
* @return {function} This returns a function that when called will wait the
|
||
|
* indicated number of milliseconds between calls before
|
||
|
* calling the original function.
|
||
|
*/
|
||
|
Function.prototype.throttle = function (milliseconds, context) {
|
||
|
var baseFunction = this,
|
||
|
lastEventTimestamp = null,
|
||
|
limit = milliseconds;
|
||
|
|
||
|
return function () {
|
||
|
var self = context || this,
|
||
|
args = arguments,
|
||
|
now = Date.now();
|
||
|
|
||
|
if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
|
||
|
lastEventTimestamp = now;
|
||
|
baseFunction.apply(self, args);
|
||
|
}
|
||
|
};
|
||
|
};
|