防“手抖”
今天去 鱼皮大佬的网站 [面试鸭] , 看到一个有意思的面试题 (手动实现’防抖’和’节流’)
接着自己去学习了一下,感觉还是挺有意思的
实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖</title>
</head>
<body>
<button class = "son">点击</button>
<script>
// 获取一下button标签
const but = document.querySelector(".son")
//定义一个功能函数
function go(){
console.log("下单啦")
}
//设置点击频率
function db(fun,time){
let timer;
return function(){
//把this 重新定义
let context = this;
let args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
fun.apply(context,args)
},time)
if(timer > 1){
console.log("请勿重复下单")
}
}
}
//使用高阶函数 侦测 db
but.addEventListener('click',db(go,1000))
</script>
</body>
</html>
最后
面试鸭里面还是有很多不错的面试题的,推荐一手
官网 :[面试鸭]