<style>
div {
width: 200px;
height: 200px;
background-color: skyblue;
margin: 50px auto;
}
</style>
<div></div>
节流:
<script>
function throttle(fn,delay){
var timer = null
return function(){
if(timer) return
timer = setTimeout(function(){
fn()
timer = null
},delay)
}
}
let fn = throttle(function(){
console.log("已经走了")
},200)
document.querySelector("div").onmouseleave = function(){
fn()
}
</script>
防抖:
<script>
function debounce(fn, delay) {
var timer = null;
return function () {
if (timer) clearTimeout(timer);
timer = setTimeout(fn, delay);
};
}
let fn = debounce(function () {
console.log("移进去了");
}, 500);
document.querySelector("div").onmouseenter = function () {
fn();
};
</script>
标签:闭包,function,防抖,节流,timer,delay,null,fn
From: https://www.cnblogs.com/sumu80/p/16599944.html