防抖的核心是,通过定时器实现,在规定时间内,频繁触发,只执行最后一次。
防抖: 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
常用在search搜索,用户在不断输入值时,用防抖来节约请求资源。
防抖函数的实现:
function debounce(func, wait) {
let timeout;
//this===obj
return function () {
//匿名函数中this指向undefined
const context = this;//this===obj
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
//匿名函数中this指向undefined
func.apply(context, args);
}, wait);
}
}
function test(name) {
console.log(this.age, name);
}
let obj = {
age: 18,
fun: debounce(test, 3000)
}
console.log(obj.fun("ha"));
结果:
节流: n 秒内只运行一次,若在 n 秒内重复触发,只有第一次生效。
使用场景:滚动加载,加载更多或滚到底部监听
function throttled2(fn, delay = 500) {
let timer = null
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args)
timer = null
}, delay);
}
}
}