您现在的位置是:首页 >技术交流 >js节流和防抖函数网站首页技术交流

js节流和防抖函数

零度忧伤宝贝 2026-04-20 12:01:05
简介js节流和防抖函数
// 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>

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。