javascript anti-shake, throttling

One, anti-shake

  1. Principle
    Trigger the same event multiple times in a short period of time, only execute the last time, or execute only the first time, and not execute the middle one. The disadvantage is that if it is triggered frequently in a short period of time, it will never be executed.
  2. Implementation
    (1) Delayed execution
    function doSomething(){
          
          
    	console.log(document.body.scrollTop);
    }
    /**
     * 函数防抖 debounce(延迟执行)
     * 在第一次触发操作时,延迟操作;后续触发操作时,判断当前是否有timer,有的话直接重置timer,进而实现防抖
     * @param { Function } _fn: 事件触发后要执行的操作
     * @param { Number } _delay: 延时(ms)
     * @return { Function }:
     */
    function debounce(_fn, _delay){
          
          
    	let timer = null;
    	return function(){
          
          
    		if(timer){
          
          
    			// 如果距离上一次触发事件的时间间隔小于delay,直接重置计时器
    			clearTimeout(timer);
    			timer = setTimeout(_fn, _delay);
    		}
    		else{
          
          
    			timer = setTimeout(_fn, _delay);
    		}
    	}
    }
    // 挂载事件监听器
    let myEventListener = debounce(doSomething, 200);
    window.addEventListener('scroll', myEventListener);
    
    (2) Execute immediately
    function doSomething(){
          
          
    	console.log(document.body.scrollTop);
    }
    /**
     * 函数防抖 debounce(立即执行)
     * 只有timer为null时,才会触发操作;若触发事件时,与上次的间隔时间小于delay,直接停止timer(此时timer仍不为null);只有当触发事件的时间与上次间隔超过delay,才会将timer设为null;
     * @param { Function } _fn: 事件触发后要执行的操作
     * @param { Number } _delay: 延时(ms)
     * @return { Function }:
     */
    function debounce(_fn, _delay){
          
          
    	let timer = null;
    	return function(){
          
          
    		let callNow = !timer;
    		if(timer) clearTimeout(timer);
    		timer = setTimeout(()=>{
          
          
    			timer = null;
    		}, _delay)
    		if(callNow) _fn();
    	}
    }
    // 挂载事件监听器
    let myEventListener = debounce(doSomething, 200);
    window.addEventListener('scroll', myEventListener);
    

Second, throttling

  1. achieve
function doSomething(){
    
    
	console.log(document.body.scrollTop);
}
/**
 * 节流函数 throttle
 * 设置阀门(vaild);在成功触发操作后,关闭阀门并在一段时间后开启,进而实现节流
 * @param { Function } _fn: 事件触发后要执行的操作
 * @param { Number } _delay: 阀门开闭最小间隔时间(ms)
 * @return { Function }:
 */
function throttle(_fn, _delay){
    
    
	let vaild = true;			// 节流阀门
	return function(){
    
    
		// 只有vaild为true时才会触发操作
		if(vaild){
    
    
			_fn();				// 触发操作
			vaild = false;		// 关闭阀门
			setTimeout(()=>{
    
    	// 一段时间后再开启阀门
				vaild = true;
			}, _delay)
		}
	}
}
// 挂载事件监听器
let myEventListener = throttle(doSomething, 200);
window.addEventListener('scroll', myEventListener);

Talking about js anti-shake and throttling
anti-shake division of immediate execution and delayed execution

Guess you like

Origin blog.csdn.net/SJ1551/article/details/109307855