From c9b6b9a5ca082fe7c1b6f58d7713f785a9eb6a5c Mon Sep 17 00:00:00 2001 From: Martial Simon Date: Mon, 15 Sep 2025 01:08:27 +0200 Subject: add: graphs et rushs --- graphs/js/throttleDebounce/throttleDebounce.js | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 graphs/js/throttleDebounce/throttleDebounce.js (limited to 'graphs/js/throttleDebounce') diff --git a/graphs/js/throttleDebounce/throttleDebounce.js b/graphs/js/throttleDebounce/throttleDebounce.js new file mode 100644 index 0000000..f6e15f9 --- /dev/null +++ b/graphs/js/throttleDebounce/throttleDebounce.js @@ -0,0 +1,48 @@ +function debounce(func, n) { + let timer = null; + + return (...args) => { + clearTimeout(timer); + timer = setTimeout(func, n, ...args); + }; +} +function throttle(func, n) { + let throttling = false; + let last_args = null; + let last_call = Date.now(); + let timeout = null; + + return (...args) => { + if (!throttling) { + last_call = Date.now(); + if (last_args) { + func.apply(this, last_args); + last_args = null; + } else { + func(...args); + } + + throttling = true; + if (timeout) { + clearTimeout(timeout); + } + + timeout = setTimeout( + () => { + throttling = false; + + if (last_args) { + func.apply(this, last_args); + } + }, + n - (Date.now() - last_call), + ); + } else { + last_args = args; + } + }; +} +module.exports = { + debounce, + throttle, +}; -- cgit v1.2.3