moodle_local_treestudyplan/amd/src/debounce.js
2023-05-17 21:19:14 +02:00

29 lines
934 B
JavaScript

/*eslint no-var: "error"*/
/*eslint no-console: "off"*/
/*eslint-env es6*/
// Put this file in path/to/plugin/amd/src
// You can call it anything you like
/**
* Limits consecutive function calls.
* @param {function} func The function to wrap.
* @param {int} wait The time limit between function calls.
* @param {bool} immediate perform the actual function call first rather than after the timout passed.
* @returns {function} a new function that wraps the debounce.
*/
function debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this, args = arguments;
let later = function() {
timeout = null;
if (!immediate){ func.apply(context, args); }
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow){ func.apply(context, args); }
};
}
export {debounce};