在前端的一些面试题中,经常会出现,hr让你手写防抖和节流算法。本文阅读仅需5分钟。
先看看基本概念:
防抖:限制函数执行次数,将多次触发变为一次触发(仅仅执行最后一次该函数的触发)
节流:限制高频执行函数的执行次数,在一定时间间隔内,将函数的触发次数降低。比如5秒内需要执行某函数50次,我可以使用节流,将函数执行次数降到5次。这样可以提高应用的性能.
防抖和节流的相同与不同之处:
相同点:防抖和节流都是减少函数的执行次数,为了提高应用的性能
不同点:防抖只是执行最后一次函数的调用。节流是减少调用次数,最后节流要调用的函数的次数往往不止一次
节流和防抖的算法,都使用了闭包思想。关于“闭包”可以看我的这篇博客闭包初学总结_m0_53498202的博客-CSDN博客
手写防抖函数:
<input type="text" />
<script>
let inp = document.querySelector("input");
inp.oninput = debounce(function () {
console.log("hello,debounce");
console.log(this.value);
}, 1000);
function debounce(fn, delay) {
let t = null;
return function () {
if (t !== null) {
clearTimeout(t);
}
t = setTimeout(() => {
fn.call(this); //现在的this才指向input
}, delay);
};
}
</script>
手写节流函数:
<script>
window.onscroll = throttle(function () {
console.log("我是节流函数" + this);
}, 500);
//
function throttle(fn, delay) {
let flag = true;
return function () {
if (flag) {
setTimeout(() => {
fn.call(this);
console.log("scroll");
flag = true;
}, delay);
}
console.log(22220);
};
}
</script>