diff options
| author | Martial Simon <msimon_fr@hotmail.com> | 2025-09-15 01:08:27 +0200 |
|---|---|---|
| committer | Martial Simon <msimon_fr@hotmail.com> | 2025-09-15 01:08:27 +0200 |
| commit | c9b6b9a5ca082fe7c1b6f58d7713f785a9eb6a5c (patch) | |
| tree | 3e4f42f93c7ae89a364e4d51fff6e5cec4e55fa9 /graphs/js/throttleDebounce/throttleDebounce.js | |
add: graphs et rushs
Diffstat (limited to 'graphs/js/throttleDebounce/throttleDebounce.js')
| -rw-r--r-- | graphs/js/throttleDebounce/throttleDebounce.js | 48 |
1 files changed, 48 insertions, 0 deletions
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, +}; |
