防抖是:用戶多次點擊后,在一定的時間內(nèi).點擊的事件只執(zhí)行一次.剩余的時間按照,最新的一次點擊重新計算
下面是一步一步按照思路寫的
function debounce(fu, time = 5000) {
let timeout = null
clearTimeout(timeout)
timeout = setTimeout(() => {
fu()
}, time)
}
function sayHai() {
console.log('hi')
}
debounce(sayHai)
debounce(sayHai)
debounce(sayHai)
問題1: 怎么計算剩余多少時間
不用計算
問題2: 如果用上邊寫的這種方式 ? 能達到效果嗎 ?
達不到效果, 用上邊的方式寫的模擬三次點擊的時候.是會執(zhí)行三次的
function debounce(fu, time = 5000) {
let timeout = null
return function () {
clearTimeout(timeout)
timeout = setTimeout(() => {
fu()
}, time)
}
}
function sayHai() {
console.log('hi')
}
debounce(sayHai)
debounce(sayHai)
debounce(sayHai)
問題3: 使用上邊的這種方式, 也不能達到效果.輸出的結果什么都沒有
function debounce(fu, time = 500) {
let timeout = null
return function () {
clearTimeout(timeout)
timeout = setTimeout(() => {
fu.apply(this, arguments); //解決this 和event的問題
}, time)
}
}
function sayHai() {
console.log('hi')
}
debounce(sayHai)
debounce(sayHai)
debounce(sayHai)
問題4: 使用這個貌似也不行可能當前的這個this, 指向就不對
用一個RN試試
下面是用RN寫的例子.達到了想要的效果:
注意點: 1、怎么用最新的點擊的開始計算時間 2、this指向(關鍵在第一個參數(shù),為了確保上下文環(huán)境為當前的this,所以不能直接用fn。)
debounce=(fu, time = 500)=> {
let timeout = null
console.log(timeout)
return function () {
clearTimeout(timeout)
timeout = setTimeout(() => {
fu.apply(this, arguments); //解決this 和event的問題
}, time)
}
}
sayHai() {
console.log('hi')
}
<TouchableOpacity onPress={this.debounce(this.sayHai)}>
<Text style={{ color: '#000' }}>測試防抖</Text>
</TouchableOpacity>
高頻事件觸發(fā),但在n秒內(nèi)只會執(zhí)行一次,所以節(jié)流會稀釋函數(shù)的執(zhí)行頻率 ,他兩的區(qū)別就是:一個是時間會按照新的點擊重新計算.而節(jié)流是
某個固定的時間只執(zhí)行一次. 實現(xiàn)方式差不多.多了一個以前是否點擊過的標記位.直接貼代碼
function throttle(fn) {
let canRun = true; // 通過閉包保存一個標記
return function () {
if (!canRun) return; // 在函數(shù)開頭判斷標記是否為true,不為true則return
canRun = false; // 立即設置為false
setTimeout(() => { // 將外部傳入的函數(shù)的執(zhí)行放在setTimeout中
fn.apply(this, arguments);
// 最后在setTimeout執(zhí)行完畢后再把標記設置為true(關鍵)表示可以執(zhí)行下一次循環(huán)了。當定時器沒有執(zhí)行的時候標記永遠是false,在
開頭被return掉
canRun = true;
}, 500);
};
}
function sayHi(e) {
console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));