防抖
防止用户频繁点击像服务器发送请求,减少服务器压力
<body>
<button>按钮</button>
<script>
let timeID
document.querySelector('button').onclick = function () {
clearTimeout(timeID)
timeID = setTimeout(function () {
console.log(111)
}, 1000)
}
</script>
</body>
节流
为减轻服务器压力,可利用开关思想,在用户第一次点击后,在单位事件内将点击事件关闭。
<body>
<button>按钮</button>
<script>
let bol = true
document.querySelector('button').onclick = function () {
if (!bol) {
return
}
bol = false
setTimeout(function () {
console.log(111)
bol = true
}, 2000)
}
</script>
</body>