DebounceとThrottleの使い分け
April 22, 2019
954
Throttle(take first): 決められた時間単位内(delay)、最初のアクションしか実行しない
function throttle(fn, delay) { let timerId; let lastExecTime = 0; return () => { const context = this; const args = arguments; let elapsedTime = performance.now() - lastExecTime; const execute = () => { fn.apply(context, args); lastExecTime = performance.now(); } if (!timerId) { execute(); } if (timerId) { clearTimeout(timerId); } if (elapsedTime > delay) { execute(); } else { timerId = setTimeout(execute, delay); } } }
Debounce(take latest): 決められた時間単位内(delay)、 何に実行されない場合、最後のアクションを実行する
function debounce(fn, interval) { let timerId; return () => { clearTimeout(timerId); const context = this; const args = arguments; timerId = setTimeout(() => { fn.apply(context, args); }, interval); } }
Demo: http://demo.nimius.net/debounce_throttle/
- 本文作者:Wenhua Chen
- 本文链接:https://wenhuachen.com/2019/04/21/Debounce%E3%81%A8Throttle%E3%81%AE%E4%BD%BF%E3%81%84%E5%88%86%E3%81%91/index.html
- 版权声明:本博客所有文章均采用 BY-NC-SA 许可协议,转载请注明出处!