防抖和节流作为前端的面试高频题目,必须要熟练掌握,不难,重在理解。
防抖
什么是防抖?
在任务频繁触发的情况下,在任务触发停止后的指定时间后执行。常应用于输入框的联想词展示。
实现防抖
思路:使用setTimeout计时器,每次触发清除掉上次的计时器开始重新计时。
setTimeout中回调后续需执行的逻辑。
防抖函数中形成了闭包,每次点击时候,执行内层函数,也就是防抖函数返回的函数体。
手写防抖函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button type="button" id="anti_shake">点我防抖!</button>
<script type="text/javascript">
window.onload = function(){
var shake = document.getElementById('anti_shake');
shake.addEventListener('click',antiShake(sayHello));
}
// 防抖函数
function antiShake(fn){
console.log('执行')
let timeout = null;
return function(){
clearTimeout(timeout);
timeout = setTimeout(()=>{
console.log(this,'call改变this指向');
fn.call(this,arguments)
},1000)
}
}
function sayHello(){
console.log('hello!hello');
}
</script>
</body>
</html>
节流
什么是节流?
指定的时间间隔内函数只执行一次。常应用于监听滚动条位置、用户提交按钮等。
实现节流
思路:利用setTimeout实现指定间隔时间内执行一次函数。 保存一个标记如果是true则执行,否则不执行,在setTimeout执行之前变为false,防止在间隔时间内多次触发点击,触发后的函数执行之后再把标记变为true。
手写节流函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="throttle">点击节流</button>
<script type="text/javascript">
window.onload = function(){
document.getElementById('throttle').addEventListener('click',throttle(sayHi));
}
function throttle(fn){
let run = true;
return function(){
if(!run){
return;
}
run = false;
setTimeout(()=>{
fn.call(this,arguments);
run = true;
},1000);
}
}
function sayHi(){
console.log('hi~hi~')
}
</script>
</body>
</html>