每天一个小知识:
1.1防抖节流:防抖(当你持续出发事件的时候,一段时间没有再触发,才会去执行某一个函数)节流(持续触发事件的时候一定时间段内只会触发一次)
1.2分别适合用在什么场景
节流:resize scroll
防抖:input
1.3 手写一个节流函数
1.3.1时间戳写法
function throttle(fn,interval){
let last = 0
return function(){
let now = Date.now()
if(now - last >= interval){
last = now
fn.apply(this,arguments)
}
}
}
function handle(){
console.log(Math.random())
}
const throttleHandle = throttle(handle,1000)
throttleHandle ();
throttleHandle ();
throttleHandle ();
throttleHandle ();
备注:apply(this,arguments) 两个参数第一个是this指向,第二个参数是参数数组可以取代参数列表
时间戳写法,第一次立即执行
1.3.2定时器写法
let timer= true
function throttle() {
if(!timer){
return false
}
timer = false
setTimeout(function () {
console.log('111')
timer = true
},1000)
}

浙公网安备 33010602011771号