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>

    运行结果

  • 相关阅读:
    图片处理工具类
    基于Redis的在线用户列表解决方案
    Windows安装Mysql5.7.10绿色版
    开启MongoDB客户端访问控制
    在Windows上安装MongoDB
    MongoDB介绍
    常用linux命令
    添加本地jar包到本地的Maven仓库以及在Maven仓库中搜索想要添加的jar包
    Centos6.5安装memcached
    Archive for required library:xxxxx/spring-beans-3.2.4.RELEASE.jar in project XXXXX cannot be read or is not a valid ZIP file
  • 原文地址:https://www.cnblogs.com/baobao0205/p/11921638.html
Copyright © 2011-2022 走看看