mirror of
https://github.com/librenms/librenms.git
synced 2024-10-07 16:52:45 +00:00
utils: throttle, debounce
This commit is contained in:
41
src/utils.js
Normal file
41
src/utils.js
Normal file
@@ -0,0 +1,41 @@
|
||||
(function(window, undefined) {
|
||||
/* Debounce and throttle functions taken from underscore.js */
|
||||
window.debounce = function(func, wait, immediate) {
|
||||
var timeout;
|
||||
return function() {
|
||||
var context = this, args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
if (!immediate) func.apply(context, args);
|
||||
};
|
||||
if (immediate && !timeout) func.apply(context, args);
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
window.throttle = function(func, wait) {
|
||||
var context, args, timeout, throttling, more, result;
|
||||
var whenDone = debounce(
|
||||
function(){ more = throttling = false; }, wait);
|
||||
return function() {
|
||||
context = this; args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
if (more) func.apply(context, args);
|
||||
whenDone();
|
||||
};
|
||||
if (!timeout) timeout = setTimeout(later, wait);
|
||||
if (throttling) {
|
||||
more = true;
|
||||
} else {
|
||||
result = func.apply(context, args);
|
||||
}
|
||||
whenDone();
|
||||
throttling = true;
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
})(window)
|
Reference in New Issue
Block a user