concept

Stabilization is delayed, and the throttle is executive, interval function throttling namely every once in a while is executed once, implementation principle to set a timer, convention XX milliseconds after the event, if the time is up, so the executive function and reset the timer, and if the difference is that if each trigger reset timer, Throttling empties the timer after the timer reaches the time limit. If the function is buffered, the function will always be delayed, causing the effect that it will not be executed. Function throttling case, the function will be executed every n seconds.

A, throttling

/** * Throttling principle: Only trigger ** once in a certain period of time@param {Function} Func Specifies the callback function to execute@param {Number} Wait delay *@param {Boolean} Immediate Whether to execute * immediately@return null* /
let timer, flag;
function throttle(func, wait = 500, immediate = true) {
	if (immediate) {
		if(! flag) { flag =true;
			// Execute immediately at the start of wait milliseconds
			typeof func === 'function' && func();
			timer = setTimeout(() = > {
				flag = false; }, wait); }}else {
		if(! flag) { flag =true
			// Execute at the end of the wait milliseconds if the execution is not immediate
			timer = setTimeout(() = > {
				flag = false
				typeof func === 'function'&& func(); }, wait); }}};export default throttle
Copy the code

Second, the image stabilization

/** * Function ** is executed only after the last operation within a specified period of time@param {Function} Func Specifies the callback function to execute@param {Number} Wait delay *@param {Boolean} Immediate Whether to execute * immediately@return null* /
let timeout = null;
function debounce(func, wait = 500, immediate = false) {
	// Clear the timer
	if(timeout ! = =null) clearTimeout(timeout);
	// Execute immediately
	if (immediate) {
		varcallNow = ! timeout; timeout =setTimeout(function() {
			timeout = null;
		}, wait);
		if (callNow) typeof func === 'function' && func();
	} else {
		// Set the timer so that the timeout will not be cleared after the last operation, so execute the func callback after the wait milliseconds
		timeout = setTimeout(function() {
			typeof func === 'function'&& func(); }, wait); }}export default debounce
Copy the code

call

// this.fun cannot be followed by ()
throttle(this.fun, 3000.true)
Copy the code