zoukankan      html  css  js  c++  java
  • 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>

    运行结果

  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/baobao0205/p/11921638.html
Copyright © 2011-2022 走看看