一、防抖
定義:觸發高頻事件後n秒內函數只會執行一次,如果n秒內高頻事件再次被觸發,則重新計算時間。
思路:每次觸發事件時都取消之前的延時調用方法
實現:
function debounce(fn) {
let timeout = null; // 創建一個標記用來存放定時器的返回值
return function () {
clearTimeout(timeout); // 每當用戶輸入的時候把前一個 setTimeout clear 掉
timeout = setTimeout(() => { // 然後又創建一個新的 setTimeout, 這樣就能保證輸入字符後的 interval 間隔內如果還有字符輸入的話,就不會執行 fn 函數
fn.apply(this, arguments);
}, 500);
};
}
function sayHi() {
console.log('防抖成功');
}
var inp = document.getElementById('inp');
inp.addEventListener('input', debounce(sayHi)); // 防抖
二、節流
定義:高頻事件觸發,但在n秒內只會執行一次,所以節流會稀釋函數的執行頻率
思路:每次觸發事件時都判斷當前是否有等待執行的延時函數
實現:
function throttle(fn) {
let canRun = true; // 通過閉包保存一個標記
return function () {
if (!canRun) return; // 在函數開頭判斷標記是否爲true,不爲true則return
canRun = false; // 立即設置爲false
setTimeout(() => { // 將外部傳入的函數的執行放在setTimeout中
fn.apply(this, arguments);
// 最後在setTimeout執行完畢後再把標記設置爲true(關鍵)表示可以執行下一次循環了。當定時器沒有執行的時候標記永遠是false,在開頭被return掉
canRun = true;
}, 500);
};
}
function sayHi(e) {
console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));
三、作爲獨立模塊實現
class EventHelper {
constructor () {
this.debounceTimer = null
this.throttleCanRun = true
}
// 防抖
debounce (fn, timeout = 500) {
// let timer = null // 創建一個變量來保存定時器返回的值
return (function () {
clearTimeout(this.debounceTimer) // 每當用戶輸入的時候把前一個 setTimeout clear 掉
// 然後又創建一個新的 setTimeout, 這樣就能保證輸入字符後的 interval 間隔內如果還有字符輸入的話,就不會執行 fn 函數
this.debounceTimer = setTimeout(() => {
fn.apply(this, ...arguments)
}, timeout)
}.call(this))
}
// 節流
throttle (fn, timeout = 500) {
// let canRun = true // 函數執行標記
return (function () {
if (!this.throttleCanRun) return // 在函數開頭判斷標記是否爲true,不爲true則return
this.throttleCanRun = false
setTimeout(() => {
fn.apply(this, ...arguments)
// 最後在setTimeout執行完畢後再把標記設置爲true(關鍵)表示可以執行下一次循環了。當定時器沒有執行的時候標記永遠是false,在開頭被return掉
this.throttleCanRun = true
}, timeout)
}.call(this))
}
}
export default new EventHelper()
使用方法:
1、先import
2、調用
示例:
import eventHelper from '@/Units/eventHelper'
eventHelper.debounce(fn)
參考文章:https://yuchengkai.cn/docs/frontend/#%E9%98%B2%E6%8A%96