函数防抖(debounce)
概念: 在事件被触发n秒后再执行回调,如果在这n秒内事件又被触发,则重新计时。
生活中的实例:电脑无操作1分钟之内如果没有操作会进入休眠,当第40秒时鼠标被移动一下,重新计时1分钟。
实现:定时器。
应用:搜索时等用户完整输入内容后再发送查询请求。
js
let inputNode = document.getElementById('user_input');
let timer;
inputNode.addEventListener('keyup',function () {
let value = inputNode.value;
if(timer){
clearTimeout(timer);
}
timer = setTimeout(()=>{
sendAjax(value);
},300) // 防抖时间一般设置为200ms-300ms
})
function sendAjax(data) {
console.log(`发送了一次Ajax请求,内容为${data}`);
}
函数节流(throttle)
概念: 规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。
生活中的实例:fps游戏,鼠标按住不松手,子弹也不会连成一条线。
实现:定时器 + 标识
应用:在鼠标滚轮滚动的时候,每隔2秒钟,打印一次
js
// 函数节流的实现;
let canLog = true;
document.body.onscroll = function () {
if(canLog){
console.log(1);
canLog = false;
setTimeout(()=>{
canLog = true;
},2000)
}
}