LoginSignup
1
0

More than 3 years have passed since last update.

lodash の備忘録

Last updated at Posted at 2019-11-08

頻繁に呼び出しが起こらないようにするためのもの。

mousemove のイベント実行など、高頻度で実行されてしまうのを回避する場合に使用するもの。

高頻度で呼ばれる例


const start = Date.now();
setInterval(
  ()=>{ console.log('', Date.now() - start); },
  0
);

↑ の場合の出力例。
〇 3
〇 5
〇 10
〇 15
・・・

_.throttle() を使う。

const start = Date.now();
setInterval(
  _.throttle( ()=>{ console.log('', Date.now() - start); }, 5000),
  0
);

↑ の場合の出力例。
〇 2
〇 5004
〇 10005
〇 15859
・・・
★ 最初に1回実行し、以降は何度呼ばれても 指定秒数(5000) 後にしか呼ばれない。

_.debounce() を使う。

const start = Date.now();
setInterval(
  _.debounce( ()=>{ console.log('', Date.now() - start); }, 5000),
  0
);

↑ の場合の出力例。
※ 一度も呼ばれない。

★ 何回呼ばれても、最後に呼ばれてから 指定秒数(5000) 経過しないと呼ばれない。

なので、上記例の場合は永遠に呼ばれない。
_.debounce()_.throttle() のどちらを使うかは、このことを考慮して使い分ける。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0