For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /note/js/throttle-debounce.md.

函数防抖

防抖函数 Debounce

问题背景

项目中,有一部分需要实现视频点播,同时在视频区域右侧也有一组视频列表,通过点击视频列表项来实现播放的视频源的切换。但是,每次触发点击事件就会触发事件函数。当多次点击的时候会多次触发封装的视频切换函数,从而导致视频解析的时候出现累加、样式未加载完从而导致样式的跑偏,影响了展示效果,也导致视频有声音无视频。为了防止多次点击,想到了函数防抖。

防抖函数实现

代码示例
const Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    return function () {
        let args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    };
};

在 Vue methods 中调用

代码示例
/**
 * switchVideo:切换视频方法
 * Debounce:防抖函数
 * time:延迟时间,默认500ms
 * */

switchVideo: Debounce(function (params) {
    // 使用箭头函数会影响 this 的指向问题
    this.getVideoInfo(params);
}, time);
注意

若多次触发 switchVideo 切换视频方法,则该函数会在点击结束后延迟 time 毫秒之后触发一次要执行的事件处理函数 getVideoInfo,从而解决多次触发事件函数的问题。