函数防抖: 任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行。
debounce(fn, delay=50) {
var timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(() =>{
fn.apply(this, arguments);
}, delay);
};
}
函数节流: 指定时间间隔内只会执行一次任务
throttle(fn, step=50) {
var bool = true, timer = null;
return function () {
if (bool) {
bool = false;
clearTimeout(timer);
timer = setTimeout(() =>{
fn.apply(this, arguments);
bool = true;
}, step);
}
};
}
example:
var i = 1;
window.onresize = this.debounce((e)=>{
console.log(i++);
},500)
// React
<div onClick={this.debounce(this.hello)}>点我</div>