vue 节流函数防抖函数封装

  • 节流
    节流的意思是,规定时间内,只触发一次。比如我们设定500ms,在这个时间内,无论点击按钮多少次,它都只会触发一次。具体场景可以是抢购时候,由于有无数人 快速点击按钮,如果每次点击都发送请求,就会给服务器造成巨大的压力,但是我们进行节流后,就会大大减少请求的次数。

  • 防抖
    防抖的意思是,在连续的操作中,无论进行了多长时间,只有某一次的操作后在指定的时间内没有再操作,这一次才被判定有效。具体场景可以搜索框输入关键字过程中实时 请求服务器匹配搜索结果,如果不进行处理,那么就是输入框内容一直变化,导致一直发送请求。如果进行防抖处理,结果就是当我们输入内容完成后,一定时间(比如500ms)没有再 输入内容,这时再触发请求。

  1. 封装

    assets/js/public.js

/**
 * 函数防抖 
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
    
    
    let delay = t || 500;
    let timer;
    return function() {
    
    
        let args = arguments;
        if (timer) {
    
    
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
    
    
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
};


/**
 1. 函数节流
 2. @param fn
 3. @param interval
 4. @returns {Function}
 5. @constructor
 */
export const Throttle = (fn, t) => {
    
    
    let last;
    let timer;
    let interval = t || 500;
    return function() {
    
    
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
    
    
            clearTimeout(timer);
            timer = setTimeout(() => {
    
    
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
    
    
            last = now;
            fn.apply(this, args);
        }
    }
}
  1. 使用
    index.vue
<script>
	import {
    
     Debounce ,Throttle } from "@/assets/js/public.js"
	
	methods:{
    
    
		// 防抖方法
		load: Debounce (function () {
    
    
			// 逻辑
		},200)

		// 节流方法
		load: Throttle(function () {
    
    
			// 逻辑
		},200)
	}
</script>

猜你喜欢

转载自blog.csdn.net/qq_41950190/article/details/108749289