函数防抖:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。通俗来讲就是:假设一个按钮在2000毫秒内被点击100次,等到最后一次触发该函数开始计时,过了delay毫秒后才会触发一次函数。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title></title>
</head>
<style>
.box{
height:3000px;
width:200px;
background-color: #ccc;
}
</style>
<body>
<script>
// 1.防抖
function debounce(fn, wait) {
let timer;
return function() {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments)
}, wait)
}
}
// window.onscroll = scorllFun
window.onscroll = debounce(scorllFun,1000)
function scorllFun(){
console.log(124)
}
</script>
<div id="app">
<div class="box"></div>
</div>
</body>
</html>
函数节流:规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。通俗来讲,就是在delay毫秒的时间内,函数只会触发一次。两次触发时间的间隔一定大于delay毫秒。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title></title>
</head>
<style>
.box{
height:3000px;
width:200px;
background-color: #ccc;
}
</style>
<body>
<script>
// // 1.防抖
// function debounce(fn, wait) {
// let timer;
// return function() {
// if (timer) clearTimeout(timer);
// timer = setTimeout(() => {
// fn.apply(this, arguments)
// }, wait)
// }
// }
// // window.onscroll = scorllFun
// window.onscroll = debounce(scorllFun,1000)
// function scorllFun(){
// console.log(124)
// }
</script>
<div id="app">
<div class="box"></div>
<button id="btn">submit</button>
</div>
<script>
// 节流
// document.getElementById("btn").onclick = submitRes
document.getElementById("btn").onclick = throttle(submitRes,1000)
function submitRes(){
console.log('触发提交按钮')
}
function throttle(fn, wait) {
let canRun = true;
return function() {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, wait)
}
}
</script>
</body>
</html>
应用场景:
防抖:
search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
节流:
鼠标不断点击触发,mousedown(单位时间内只触发一次)
监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断
原文链接:https://blog.csdn.net/welnee/article/details/108688363