节流throttle
当频繁触发一个函数的时候,在规定时间内,只有第一次生效。
比如,滚动事件,请求数据。
<body>
<div id="hehe" style="height: 10000px;">hehe</div>
</body>
<script>
function throttle(fun,delay){
let lasttime=0;
return function (params) {
let nowtime=Date.now();
if(nowtime-lasttime>delay){
fun();
lasttime=nowtime;
}
}
}
function fun(){
console.log('throttle')
}
document.onscroll=throttle(fun,2000)
</script>
防抖debounce
当频繁触发一个函数的时候。如果触发一个函数,在规定的时间内,又再次触发,那就取消第一次的,重新开始计时,如果规定时间内,又有触发,再次取消上一次的,重新计时,只有最后一次生效。
<body>
<div id="search">search</div>
<input type="text" id="textcontent">
</body>
<script>
function debounce(fun,delay){
let timer=null;
return function (params) {
clearTimeout(timer);
timer=setTimeout(() => {
fun();
}, delay);
}
}
function fun(){
console.log('http request')
}
document.getElementById('search').onclick=debounce(fun,2000)
</script>