关于javascript:节流防抖

5次阅读

共计 1147 个字符,预计需要花费 3 分钟才能阅读完成。

防抖

需要场景:

当用户频繁点击一个申请按钮时,如果不做任何解决,那么点了多少次,这个按钮绑定的申请事件就会执行多少次。

解决方案一 :在申请前 设置按钮 diable 状态为 true, 申请完结后设置 disable 状态 false。

解决方案二 :写一个防抖函数,比方点击这个按钮 1 秒后再去提交申请。

<button id="save"> 保留 </button>
<script>
        // 防抖
        let btn = document.getElementById('save');
        let timer = null;
        btn.onclick = function (){ 
            // 只有触发该事件,立刻进行这个 timer
            clearTimeout(timer)
            // 在 1000ms 后再去执行其余操作
            timer = setTimeout(() => {console.log('提交申请');
            }, 1000);
        }
</script>

另外附上我在理论我的项目中的案例

// 创立一个 debounce.js

/**
 * 防抖函数(避免用户短时间频繁操作按钮)* @param fn 要执行的函数
 * @param delay 延迟时间(ms)*/
export default function onDebounceFn(fn, delay = 300) {clearTimeout(window.debounceTimer);
    window.debounceTimer = setTimeout(() => {fn(); 
    }, delay);
}
// 在 vue 组件中

/**
 * 搜寻事件
 */
onSearch() {
    this.searchKeyWord = this.searchInputValue;
    this.currentPage = 1;
    // onDebounceFn 曾经绑定在了实例原型上,这里间接应用 this.$onDebounceFn
    this.$onDebounceFn(this.getLiveList);
},

节流

需要场景:

举例:拖动一个 div, 在 div 被拖动过程中执行一个函数,为了简化代码,我这里以鼠标在挪动过程中触发某个动作(事件 / 办法 / 函数 …)作为例子。
试比拟如下两个例子

实现节流前:

window.addEventListener("mousemove",mousemoveFn);

function mousemoveFn() {console.log("鼠标正在挪动中..."); // 触发内容
}

实现节流后:

window.addEventListener("mousemove",mousemoveFn);

let flag = true;

function mousemoveFn() {if(flag){
        flag = false
        setTimeout(() => {console.log("鼠标正在挪动中...");
            flag = true
        }, 500);
    }
}

正文完
 0