JavaScript计时器、防抖、节流
计时器方法
1 2 3 4 5 6 7 8
| setInterval(function, millisecond)
clearInterval(timer)
setTimeout()
clearTimeout()
|
防抖与节流
防抖(debounce):防止短时间内多次触发事件,只触发最后一次。
节流(throttle):防止短时间内多次触发事件,但是间隔事件内,还是需要不断触发。
通过“计时器”可以实现防抖与节流。
防抖
触发事件会导致重新计时,计时走完才会执行一次操作。
会重置定时器
示例:
1 2 3 4 5 6 7 8 9 10 11
| let timer = null; window.onscroll = function() { if (timer !== null) { clearTimeout(timer) } timer = setTimeout(()=>{ console.log("防抖操作"); timer = null; }, 500); };
|
利用闭包封装防抖算法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function debounce(fun) { let timer = null; return function() { if (timer) { clearTimeout(timer); timer = null; } timer = setTimeout(()=>{ fun(); }, 500); } }
|
真实场景:
节流
每隔一段时间才可以触发一次操作。其他时间的会被拦截。
示例:
1 2 3 4 5 6 7 8 9 10 11
| let mark = true; window.onscroll = function() { if(mark) { setTimeout(()=>{ console.log(); mark = true; }, 500); } mark = false; };
|
利用闭包封装节流算法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function throttle(fun) { let mark = true; return function() { if(mark) { setTimeout(()=>{ fun(); mark = true; }, 500); } mark = false; }; }
|
真实场景: