Image stabilization

define

A callback is executed after the event is triggered for a certain period of time. If the event is triggered again during this period, the time is recalculated.

Read a classic explanation: the function of the tremble is the master hair skills to read, read skills will be read by skills.

implementation

export function debounce(fn, wait) {
  let timer = null;
  return function () {
      const context = this
      const args = arguments
      if (timer) {
          clearTimeout(timer);
          timer = null;
      }
      timer = setTimeout(function () {
          fn.apply(context, args)
      }, wait)
  }
}
Copy the code

Application scenarios

Buttonless search box

If we don’t add stabilization, then the callback will be called every time we type, which is obviously not reasonable. We just need to call the callback function after we type.

So let’s add an anti-shake function to stop calling after 500ms to avoid repeated useless calls.

Function ajax(content) {console.log(' Ajax request '+ content)} function debounce(fun, Delay) {return function (args) { ClearTimeout (fun.id) fun.id = setTimeout(() => {fun.call(this, args)}, clearTimeout(fun.id) => {fun.call(this, args)}, Let debounceAjax = debounce(ajax, 500) let inputb = document.getElementById('debounce') inputb.addEventListener('keyup', function (e) { debounceAjax(e.target.value) })Copy the code

Music player progress bar

If we do not add anti-shake, the music progress will be constantly updated when dragging the music progress bar, resulting in discomfort for the audience.

Then, we added the anti-shake function, stopped dragging for 300ms to retrieve the music progress update, so as to avoid frequent music progress update.

The throttle

define

Events are raised multiple times in a period of time, and only the first event is called back.

implementation

export function throttle(fn, gapTime) { let _lastTime = null; Return function () {// + new Date() converts time to seconds // + converts elements to Number type let _nowTime = + new Date() if (_nowTime - _lastTime > gapTime || ! _lastTime) { fn(); _lastTime = _nowTime } } }Copy the code

Application scenarios

Mouse scroll bar

If we don’t add throttling, the scrolling event will be triggered over and over again during the mouse scroll, which will degrade performance if we do something here.

So let’s add a throttling function to trigger the callback repeatedly for 1s, only the first trigger will call the callback, to avoid the problem of constantly firing events.