Detailed explanation of JavaScript anti shake and throttling

  • 2021-11-29 06:05:37
  • OfStack

Directory anti-shake debounce throttling throttle summary

Anti-shake debounce

Definition: For events triggered continuously in a short time, such as scrolling events, anti-shake means that the event handler only executes once within a certain time limit.

With regard to anti-shake, take the finger pressing spring for example, press the spring with your finger, 1 press it straight, and the spring will not bounce until you release your finger.

Example resize:


function debounce(fn, wait){
    var timer = null;
    return ()=>{
        if(timer !== null){
            clearTimeout(timer);
        }
        timer = setTimeout(fn, wait);
    }
}
function handle(){
    console.log(Math.random());
}
window.addEventListener("resize",debounce(handle, 1000));

The above is not an immediate execution version

Immediate execution version


function debounce(fn, wait){
	let timeid, flag = true;
	return () => {
		clearTimeout(timeid);
		if(flag){
			fn();
			flag = false;
		}else{
			timeid = setTimeout(()=>{
				flag = true;
			}, wait);
		}
	}
}

Drag the browser window to trigger resize. At this time, handle function is not triggered. Timer timers time. If resize is triggered again within the timing time, it will be timed again. The advantage of this is that dragging the browser window to trigger resize will not frequently execute handle function, but only let it run when it needs to be executed, effectively removing redundancy.

Common writing:


const debounce = (func, delay = 200) => {
  let timeout = null
  return function () {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(this, arguments)
    }, delay)
  }
}

Throttle throttle

Definition: Let the event be executed only once in a specified time.

The original intention is to execute only once within the specified time, like the water drop of a faucet, so as to reduce frequent and repeated execution.

Such as the search box input event.

Calculated by timestamp:


function throttle(fn,wait){
  let startTime = 0;
  return function(){
    let endTime = Date.now();
    if(endTime-startTime>wait){
      fn();
      startTime = endTime;
    }
  }
}

Through the timer:


function throttle(fn,wait){
  let timeid = null;
  return function(){
    if(!timeid){
       timeid = setTimeout(function(){
         fn();
         timeid = null;
       },wait)
    }
  }
}

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: