防抖(只执行最后一次)
<!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>Document</title>
</head>
<body>
<button>点我试试</button>
<script>
var btn = document.querySelector('button')
var timer = null
btn.onclick = function() {
clearTimeout(timer)
timer = setTimeout(() => {
console.log('发送请求了');
}, 500)
}
</script>
</body>
</html>
节流(减少执行频率次数)
<!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>Document</title>
</head>
<body>
<button>点我试试</button>
<script>
var btn = document.querySelector('button')
var flag = true
btn.onclick = function() {
if (flag) {
flag = false
console.log('发送请求了');
setTimeout(() => {
flag = true
}, 1000);
}
}
</script>
</body>
</html>
应用场景
1.鼠标跟随
2.页面滚动、缩放
3.防止重复调接口
4.搜索框查询
区别
防抖:一段时间内只执行一次。
节流:一段时间内,会产生多次效果,只不过每一次之间得频率降低了。