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/