Debounce (Anti-shock function)

function debounce(fn,delay){
	let timer = null;
	return function(){
		clearTimeout(timer);
		timer = setTimeout(()=>{
			fn.apply(this,arguments)
		},delay)
	}
}
Copy the code

Stabilization function: execute the callback function n seconds after the event is triggered. If it is triggered again within n seconds, the timer is reset

Usage Scenarios:

  • After the user enters a string of characters in the input box, only the last Query Ajax request will be executed after the input, which can effectively reduce the number of requests and save request resources.

  • Window resize, Scroll events, constantly adjust the size of the browser window, or trigger the corresponding event when scrolling, so that it only trigger once;

You’re throttle.

function throttle(fn,time){ let flag = true; return function(){ if(! flag) return; // Flag = false; SetTimeout (()=>{fn.apply(this,arguments) flag=true; // Only when the timer event is triggered and the flag changes to true, can the next timer be executed},time)}}Copy the code

Timestamp mode:

function throttle(fn,time){ let pre = Date.now(); Return function(){let cur = date.now (); If (cur-pre>time){setTimeout(()=>{fn.apply(this,arguments); pre=cur; // Update the last time},time)}}}Copy the code

Throttling function: specifies a unit of time within which only one event callback can be executed. If an event is triggered more than once in the same unit of time, only one event can take effect.

Application scenarios

  • The mouse triggers an event (such as a click) continuously, only once per unit of time;
  • In the infinite loading scenario of the page, the user should send ajax requests every once in a while while scrolling the page, instead of requesting data when the user stops scrolling the page.
  • Listen for rolling events, such as whether to slide to the bottom and automatically load more, using throttle;

Anti-shake is to maintain a timer that is specified to trigger the function after the delay time. However, if triggered again within the delay time, the current timer will be cleared and the timeout call will be reset, that is, the timer will be reset. In this way, only the last operation can be triggered. The throttling function determines the difference between the current time and the last time through a timestamp. If triggered after time, the last time is updated.