作用:可以降低事件中代码的执行频率
<body>
<button>点击</button>
<script>
let flag = true //初始化节流阀,默认打开阀门
function throttle () {
if (flag) {
flag = false //事件被触发后立即关闭阀门
console.log("点击一次后,需要等待2秒后,再次点击才可以执行");
setTimeout(() => {
flag = true
}, 2000);
}
}
// 绑定事件
document.querySelector("button").addEventListener("click", throttle)
</script>
</body>