js节流和防抖函数

掌握JavaScript节流与防抖技术
// utils.js
// 防抖函数
export function debounce(func, delay) {
    let timer;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}

// 节流函数
export function throttle(func, delay) {
    let lastTime = 0;
    return function() {
        const context = this;
        const args = arguments;
        const now = new Date().getTime();
        if (now - lastTime >= delay) {
            func.apply(context, args);
            lastTime = now;
        }
    };
}

main.js中挂载到 Vue 原型

import Vue from 'vue';
import { debounce, throttle } from './utils';

// 将防抖函数挂载到Vue原型
Vue.prototype.$debounce = debounce;
// 将节流函数挂载到Vue原型
Vue.prototype.$throttle = throttle;

import App from './App.vue';

Vue.config.productionTip = false;

new Vue({
    render: h => h(App),
}).$mount('#app');

在 Vue 组件中使用

<template>
    <div>
        <input type="text" @input="handleInput">
        <button @click="handleClick">点击</button>
    </div>
</template>

<script>
export default {
    methods: {
        handleInput() {
            // 使用防抖函数
            this.$debounce(this.doSearch, 500)();
        },
        doSearch() {
            console.log('执行搜索操作');
        },
        handleClick() {
            // 使用节流函数
            this.$throttle(this.doSomething, 1000)();
        },
        doSomething() {
            console.log('执行一些操作');
        }
    }
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值