1.為什么使用防抖和節流
對於頻繁觸發的事件 比如keydown keyup事件 當頻繁點擊時候 會多次觸發事件 頁面出現卡頓 影響性能
2.函數防抖(debounce):間隔時間內只執行一次 函數節流(throttle):間隔時間內執行
3.使用場景
函數防抖:搜索框等
函數節流:鼠標不斷點擊事件等
4.目的
提升性能 提高用戶體驗
5.用react實現防抖和節流
import React, { Component } from "react";
class UnDebounce extends Component {
constructor(props) {
super(props);
this.state = {
timerId: null, //整數 定時器的編號 用來取消這個定時器
}
}
//模仿ajax請求
ajax = (content) => {
console.log('ajax:' + content)
}
debounce = (fn, delay = 3000) => {
//期間間隔執行 節流
return (...rest) => { //箭頭函數是沒有arguments的 所以用...rest 來代替
let args = rest;
if (this.state.timerId) clearTimeout(this.state.timerId);//要用this.timerId 而不能直接定義var timerId=null;
this.state.timerId = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
throttle = (fn, delay = 3000) => {//
//期間間隔執行 節流
let canRun = true;
return (...rest) => {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, rest);
canRun = true;
}, delay)
}
}
onUndebounceKeyUpClick = (e) => {//只要是按下鍵盤就會發生ajax請求 會出現資源浪費 一般情況下當輸入完整字符才會請求數據
this.ajax(e.target.value)
}
onDebounceKeyUpClick = (e) => {//加入防抖動后 在頻繁輸入后 不會發送請求
let debounceAjax = this.debounce(this.ajax, 3000)
debounceAjax(e.target.value)
}
onThrottleKeyUpClick = (e) => { //ajax會按照我們設定的時間,每1s執行一次
let throttleAjax = this.throttle(this.ajax, 3000);
throttleAjax(e.target.value)
}
render() {
return (
<div>
正常input:<input onKeyUp={this.onUndebounceKeyUpClick} />
防抖動的input:<input onKeyUp={this.onDebounceKeyUpClick} />
節流的input:<input onKeyUp={this.onThrottleKeyUpClick} />
</div>
);
}
}
export default UnDebounce;
6.使用lodash實現防抖和節流
import _ from 'lodash';
實現防抖 :onClick = { _.debounce(this.ajax, 200)}
實現節流 :onClick = { _.throttle(this.ajax, 200)}
