节流
节流概念 节流:N秒内只运行一次,诺在N秒内重复触发,只有第一次生效,可以减少不必要的网络请求和事件挤压,减少服务器负担,提高性能。
应用场景:
- 滚动加载:监听页面滚动到底部的时候触发
- 拖拽场景:固定时间只执行一次,防止高频率的位置变动
方法一
<script>
function coloring () {
let r = Math.floor( Math.random() * 255)
let g = Math.floor( Math.random() * 255)
let b = Math.floor( Math.random() * 255)
document.body.style.background = `rgb(${r},${g},${b})`;
}
function throttle (func,delay) {
let timer; // 将timer设置在外围,方便闭包调用和修改
return function () {
let context = this
let args = arguments
if(timer){ // 判断 timer 是否被赋值,被赋值直接返回出去
return
}
timer = setTimeout(function () {
func.apply(context,args);
timer = null;
},delay)
}
}
window.addEventListener('resize',throttle(coloring,2000));
</script>
方法二
<script>
function coloring () {
let r = Math.floor( Math.random() * 255)
let g = Math.floor( Math.random() * 255)
let b = Math.floor( Math.random() * 255)
document.body.style.background = `rgb(${r},${g},${b})`;
}
function throttle (func,delay) {
let per = 0; // 初始化时间
return function () {
let now = new Date() // new一个当前时间
let context = this;
let args = arguments;
if(now - per > delay){ // 判断当 now的时间减去 per初始时间 大于设定的间隔时间就执行函数小于就不执行,并将now赋值给per
func.apply(context,args);
per = now // 执行函数将 now 赋值给 per
}
}
}
window.addEventListener('resize',throttle(coloring,2000));
</script>
图示讲解原理
防抖
什么是防抖:
- 防抖策略 (debounce)当事件被触发时,延迟N秒才执行,如果在这N秒内再次被触发将重新计时
好处
能够保证用户在频繁触发某些事件的时候,不会频繁的执行回调,只会被执行一次
防抖的应用场景
- 用户在输入框中连续输入一串字符时,可以通过防抖策略,只在输入完后,才执行查询的请求,这样可以有效减少请求次数,节约请求资源;
<script>
let button = document.querySelector('button')
function onClick() { // 执行函数
console.log('已剁手');
}
function debounce(func, delay) { // 防抖函数
let timer; // 将变量timer定义在外部函数内,方便闭包调用
return function () {
let context = this // 获取指向button按钮的this,让this始终指向点击按钮
let args = arguments // 传入的参数
clearInterval(timer) // 清除计时器
timer = setTimeout(function () {
func.apply(context, arguments)
}, delay)
}
}
button.addEventListener('click', debounce(onClick, 2000)) // 用按钮节点调用防抖函数,设置时间间隔为2000毫秒
</script>