在开发过程好中往往为了性能考虑某些频发事件需要降低其触发频率,
so:
函数节流:
// 第一种函数节流
const throttle = function(fn,delay) {
let timer = null
return function() {
const context = this
let args = arguments
if(!timer) {
timer = setTimeout(() => {
fn.apply(context,args)
clearTimeout(timer)
timer=null;
},delay)
}
}
}
function drag(){
console.log("节流函数触发!!");
}
document.onclick=throttle(drag,2000)
// 方法二:时间戳
const throttle2 = function(fn, delay) {
let preTime = Date.now()
return function() {
const context = this
let args = arguments
let doTime = Date.now()
if (doTime - preTime >= delay) {
fn.apply(context, args)
preTime = Date.now()
}
}
}