イベント間引き処理とは
scrollイベントなどを使用したときはイベントを連続して呼び出してしまうので処理が多くなり、ブラウザに負荷がかかる。
// <p id="r"></p> var r = document.getElementById('r') function insertHello() { r.textContent += 'hello! ' } window.addEventListener('scroll', insertHello)
そのため負荷軽減のため、イベントの呼び出しは指定した時間が経過した際に発生するようthrottleやdebounceを使用して処理することがある。
一般的にはlodashのthrottleやdebounceが使用されることが多い。
throttleとは
イベントを呼び出し後、指定した時間が経過するまでは次のイベントを発生させない処理。
使い方は以下のようにthrottleに処理する関数と時間を入れるだけだ。
lodashを使用する場合
// <p id="r"></p> var r = document.getElementById('r') function insertHello() { r.textContent += 'hello! ' } var hello = _.throttle(insertHello, 1000) window.addEventListener('scroll', hello)
lodashを使用しない場合
// <p id="r"></p> var r = document.getElementById('r') function insertHello() { r.textContent += 'hello! ' } var throttle = function(fn, interval) { var lastTime = Date.now() - interval return function() { if ((lastTime + interval) < Date.now()) { lastTime = Date.now() fn() } } } var hello = throttle(insertHello, 1000) window.addEventListener('scroll', hello)
debounceとは
イベントを呼び出し後、次のイベントまで指定した時間が経過するまではイベントを発生させない処理。
1000ミリ秒を指定しても500ミリ後にイベントが発生したら1000ミリ秒にリセットされ1000ミリ秒以上経過しなければイベントが発生しない。
lodashを使用する場合
// <p id="r"></p> var r = document.getElementById('r') function insertHello() { r.textContent += 'hello! ' } var hello = _.debounce(insertHello, 1000) window.addEventListener('scroll', hello)
lodashを使用しない場合
// <p id="r"></p> var r = document.getElementById('r') function insertHello() { r.textContent += 'hello! ' } var debounce = function(fn, interval) { var timer return function() { clearTimeout(timer) timer = setTimeout(function() { fn() }, interval) } } var hello = debounce(insertHello, 1000) window.addEventListener('scroll', hello)