Image stabilization

Debounce

  • The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculated.

Where can anti – shake be used?

  • Action buttons, search boxes…
function debounce(handler, dely = 800){
let timer = null;
  return function(){ clearInterval(timer); timer = setTimeout(() => { handler.apply(this, arguments); }, dely); }}Copy the code

The throttle

The throttle (thorttle)

  • High frequency events fire, but only execute once in n seconds, so throttling dilutes the frequency of the function’s execution.
function throttle(handler, wait = 800) {
  let lastTime = 0;
  return function () {
    let newTime = new Date().getTime();
    if (newTime - lastTime > wait) { handler.apply(this, arguments); lastTime = newTime; }}}Copy the code

Anti-shake & throttling

The difference between anti-shake and throttling

  • Anti-jitter means to turn multiple executions into the last one, and throttling means to turn multiple executions into periodic executions.

Why anti-shake and throttling?

  • This relieves server pressure and prevents multiple requests from being sent to the server due to frequent user operations.
  • We often need to bind events that are constantly firing, but we don’t want to execute functions that often while events are constantly firing.