定义和应用场景
节流和防抖的作用都是对于频繁连续触发的事件做性能上的优化,两者的区别和应用场景: 1、节流:在连续触发的事件上,只有指定的时间内触发一次,应用场景如:滚动事件,鼠标移动事件 2、防抖:在连续触发的事件上,不管连续触发的多长时间,只有在一定间隔后才会执行一次,没有在指定间隔时间内触发了事件,则会重新清除事件重新执行。应用场景如:输入框搜索的输入事件、点击按钮请求事件
节流函数的实现
index.js
/**
* @function 函数节流 (用于鼠标移动事件,窗口滚动事件,在规定的一段时间内只执行一次)
* @param callback 节流的回调函数
* @param time 节流时间
*/
function throttle(callback,time){
let oldTime = null
return function(e){
let nowTime = new Date()
if(nowTime - oldTime > time){//判断时间间隔是否为time,是则执行
callback.apply(this,e)
oldTime = nowTime
}
}
}
html部分
<body>
<div id="test" style="width: 500px;height: 500px;background-color: pink;margin-top: 20px;"></div>
<script src="./index.js"></script>
<script>
let test = document.getElementById('test')
test.addEventListener('mousemove',throttle(function(e){
console.log('滚动',e)
},1000))
</script>
</body>
防抖函数的实现
index.js
/**
* @function 函数防抖 (用于输入框搜索以及按钮点击支付,用户的持续操作在规定时间以内触发取消事件重新执行)
* @param callback 防抖的回调函数
* @param time 防抖时间
*/
function debunce(callback,time){
let timer = null
return function(e){
if(timer){//如果上次的执行回调有就清空后面的只执行一次
clearTimeout(timer)
}
timer = setTimeout(()=>{
console.log('e2',e)
callback.call(this,e)
//执行完的定时器清空
timer = null
},time)
}
}
html部分
<body>
<input type="text" id='testInput'>
<script src="./index.js"></script>
<script>
let testInput = document.getElementById('testInput')
testInput.addEventListener('input',debunce(function(e){
console.log('输入事件',e)
},1000),args)
</script>
</body>