防抖:debounce(不停滑动鼠标时,数字不会累加,当停止滑动,1000ms之后数字才会累加)
let num = 1;
let div= document.getElementById('myDiv');
function count() {
div.innerHTML = num++;
};
div.onmousemove = debounce(count, 1000);
//防抖非立即执行函数
function debounce(func, wait) {
let timeId = null;
return function(){
let context = this;
let args = arguments;
if (timeId) {
clearTimeout(timeId);
}
timeId = setTimeout(() => {
func.apply(context,args);
}, wait)
}
}
节流:throttle(下面的效果:不停滑动鼠标时,数字也会累加,因为到了某个时刻now-prev的差会大于wait)
let num = 1;
let div= document.getElementById('myDiv');
function count() {
div.innerHTML = num++;
};
div.onmousemove = throttle(count, 1000);
//节流时间戳版本
function throttle(func,wait){
let prev = 0;
return function(){
let arg = arguments;
var now = Date.now();//时间戳一串长数字
let context = this;
if((now - prev)>wait){
func.apply(context,arg);
prev = now;
}
}
}