Function stabilization

Function stabilization: for some == frequent == operations, == only perform == once (first or last time) within a certain period of time ==. Scenario description: For example, a button click event in a page, usually a click event is bound to the button, and then when we click the button it will trigger the event and perform some function code (such as request background API). Under normal circumstances, we are triggered by clicking once, but it does not rule out someone malicious keep clicking the button, so it will not stop to request the background API, is bound to cause certain pressure to the server, so in order to prevent this frequent operation, the function is born. Implementation idea: use closure mechanism

  • You need to set up a wait to execute code only once, and set up a timer for timing
  • The first time we click the button to trigger the event, we start timing (a timer is required here) and wait this long
  • During this wait, the function code is automatically executed when the wait time is over
  • If a second event is triggered during this wait, the original timer is cleared, the timer is restarted and the code is not executed until the wait is not triggered frequently during this time.

Usage scenario: Used for button click events

Function syntax: @params

  • Func [function] : The function to fire, the function that actually executes the function code
  • Wait [number] : indicates the wait time
  • Immediate [Boolean] : A switch can be added to identify the first or last execution of a frequent operation

@return

  • A function that can be called to execute
<button id="submit"></button>
Copy the code
// By default, only the first click takes effect within that time.
function debounce(func, wait = 300, immediate = true){
	let timer = null;
	return function anonymouse(. params){
		// Each click must clear the timer and restart the wait
		clearTimeout(timer);
		// If the timer is not null, it means that the timer is frequently clicked. If the timer is frequently clicked, it needs to be recalculated and func only needs to be executed once
		// The timer is reset to null when the wait time is up
		letnow = immediate && ! timer; timer =setTimeout(() = > {
			// When the waiting time is up, reset the timer to NULL to identify if it is the first click of the next round of frequent clicks
			timer = null;
			// We call func this way because we don't want to change the reference to this in the original function
			// The current anonymous function is triggered by a button, so this refers to the button that triggered the event.
			// If func is bound to the button without the function's anti-shock mechanism, this in func is also the button that triggers the event.
			// So if you call func directly, this in func will refer to window.
			// If immediate is true, it is executed on the first trigger! immediate ? func.call(this. params) :null;
		},wait);
		
		// If immediate is true, the function is invoked to identify the first trigger
		now ? func.call(this. params) :null; }}function handle(){
	console.log(this);
	/ / call the API...
}

submit.onclick = debounce(handle, 300.true);
Copy the code

Function throttling

Function throttling: Throttling is a preset period of time during a frequent operation to prevent the code from executing frequently, and then the code is executed at preset intervals. Scenario Description: For example, the page scroll event, when we drag the scroll bar, the corresponding scroll bar event code will be continuously executed, each scroll process, the browser’s fastest response time is generally 5~6ms, and as long as 5~6ms, the corresponding function will be triggered to execute. So in order to make the code execute less frequently, we use function throttling to control. Implementation idea: use closure mechanism

  • You need to set up a wait (how often the code can be executed) and set the timer timer to be used for timing
  • When the scroll bar is first rolled, note the current time now and set previous to 0 to ensure that the first scroll will be executed once
  • The interval wait subtracts the current time now and the previous time, which is the remaining time of remaining from the preset time
  • If remaining is less than or equal to 0, it indicates that the interval between two function executions has passed the preset interval, and the next execution can be performed

Calls the concrete execution function func with the current time now assigned to previous as the last execution time

  • If remaining is greater than 0 and the timer is empty (not set or manually cleared), the interval is not up and the timer countdown is not set. In this case, it is necessary to set a timer to start the countdown, and the countdown time is the remaining time. If the timer ends, the code can be executed again and the timer can be cleared for the next timer setting. The current execution time is then assigned to previous as the last execution time to be used.

Usage scenario: Generally used for fuzzy matching in the process of page scrolling and text box input

Function syntax: @params

  • Func [function] : The function to fire, the function that actually executes the function code
  • Wait [number] : indicates the interval

@return

  • A function that can be called to execute
function throttole(func, wait){
	let timer = null,
		previous = 0;
	return function anonmouse(. params){
		let now = new Date(),
			remaining = wait - (now - previous);
		if(remaining <= 0) {// The interval between two executions has exceeded the set interval
			// Assigns the current execution time as the last execution time to Previous
			previous = now;
			// Cancel the countdown because it has already been executed
			clearTimeout(timer);
			// Clear the timer after execution, so that the timer can be set next time
			timer = null;
			func.call(this. params); }else if(! timer){// The time difference between the two executions has not reached the preset interval, and the timer countdown is not set;
		// Set the timer to start the countdown, the end of the time can be executed again
		// If the timer is set, no more processing is done.
			timer = setTimeout(() = > {
				// Clear the timer after execution, so that the timer can be set next time
				timer = null;
				// Assigns the current execution time as the last execution time to Previous
				previous = new Date(a); func.call(this. params); }, remaining); }}}function handle(){
	console.log(this);
	//dosomthing.....
}

document.body.onscroll = throttole(handle, 500);
Copy the code