JS 节流
说明:
1.对于高频触发的监听事件函数,实现对于触发次数的间接限制,从而降低触发次数.
2.关键点在于控制时间周期内,阻止触发内容,即上锁;在时间周期外解锁,触发内容。
3.主要是对间隔时间限制,在规定时间内,阻止触发事件内指定程序或默认抛弃
4.三种实现节流方式:时间戳版,定时器版,束流版
5.相当于"技能冷却时间"
初始化代码
<style>.wrap {margin: 20px auto;width: 400px;height: 250px;box-shadow: 0 0 4px #333;color: #08d;font-size: 40px;font-weight: 800;display: flex;justify-content: center;align-items: center;cursor: pointer}
</style>
<body><div class="wrap">0</div>
</body>

时间戳版
<script>
//时间戳版let oWrap = document.querySelector(".wrap")let count = 0let time = 0//时间戳版oWrap.addEventListener("mousemove", function () {if (Date.now() - time < 1000) {return false;}time = Date.now()write()}, false)function write() {oWrap.innerText = count++}
</script>
定时器版
//定时器版let oWrap = document.querySelector(".wrap")let count = 0let lock = falseoWrap.addEventListener("mousemove", function () {if (lock) {return true}lock = truewrite()//控制再次触发时间间隔setTimeout(() => {lock = false}, 1000);}, false)function write() {oWrap.innerText = count++}
束流版
//束流版let oWrap = document.querySelector(".wrap")let count = 0let num = 0oWrap.addEventListener("mousemove", function () {num++if (num % 100 !== 0) {return false;}write()}, false)function write() {oWrap.innerText = count++}
效果
当鼠标在div元素上移动时,触发mousemove事件,通过三种节流函数控制,“限制”在规定时间内触发write函数,从而“防止”元素内的数字快速增加。















