vue 防抖和节流

函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

函数节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

js代码

/**
 * @desc 函数防抖
 * @param fn 函数
 * @param delay 延迟执行毫秒数 默认0.5s
 */
export function debounce(fn, delay) {
    var delay = delay || 500;
    var timer;
    return function () {
            console.log('调用了debounce方法')
            let args = arguments;
            if(timer){
                    clearTimeout(timer);
            }
            timer = setTimeout(() => {
                    timer = null;
                    fn.apply(this, args);
            }, delay);
    }
}

/**
 * @desc 函数节流
 * @param fn 函数
 * @param interval 函数执行间隔时间毫秒数 默认1s
 */
export function throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 1000;
    return function () {
            console.log('调用了throttle方法')
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}

在vue中使用

<template>
    <view>
        <text @tap="clickDebounce()">防抖</text>
        <text @tap="clickThrottle()">节流</text>
    </view>
</template>

<script>
    import { debounce, throttle } from '@/utils/index.js'
    export default {
        data() {
            return {
                num: 0
            }
        },
        methods: {
            // 防抖
            clickDebounce: debounce(function() {
                this.num += 1
                console.log('' + this.num +'次点击' )
            }, 600),
            // 节流
            clickThrottle: throttle(function() {
                this.num += 1
                console.log('' + this.num +'次点击' )
            }, 800)
        }
    }
</script>

运行结果

原文地址:https://www.cnblogs.com/baobao0205/p/11921638.html