js 防抖 debounce 与 节流 throttle
debounce(防抖) 与 throttle(节流) 主要是用于用户交互处理过程中的性能优化。都是为了避免在短时间内重复触发(比如scrollTop等导致的回流、http请求等)导致的资源浪费问题。
debounce与throttle的区别主要在于:
1. debounce是通过设置定时器,在延迟的时间内每次触发都会重置定时器,直到在某个延迟时间点内不再触发事件才会执行。
2. throttle也是通过设置定时器,只是在延迟时间内用户只有首次触发是有效的,其他触发都是无效的,只有等延迟时间到了才会执行该事件。
理论有点枯燥,直接看代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>debounce</title> 5 <style type="text/css"> 6 #box { 7 width: 300px; 8 height: 150px; 9 border: 1px solid #eee; 10 background-color: #e3e3e3; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="box"></div> 16 17 <script type="text/javascript"> 18 let divEle = document.querySelector('#box'); 19 let count = 0; 20 divEle.addEventListener('mousemove', debounce(cbFn, 1000)); 21 22 function debounce(callback, delay) { 23 let timer = null; 24 return function() { 25 timer && clearTimeout(timer); 26 timer = setTimeout(function(){ 27 callback.apply(); 28 }, delay) 29 } 30 } 31 32 function cbFn() { 33 divEle.innerHTML = ++count; 34 } 35 </script> 36 </body> 37 </html>
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>throttle</title> 5 <style type="text/css"> 6 #box { 7 width: 300px; 8 height: 150px; 9 border: 1px solid #eee; 10 background-color: #e3e3e3; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="box"></div> 16 17 <script type="text/javascript"> 18 let divEle = document.querySelector('#box'); 19 let count = 0; 20 divEle.addEventListener('mousemove', throttle(cbFn, 1000)); 21 22 function throttle(callback, delay) { 23 let preTime = new Date().getTime(); 24 return function() { 25 const now = new Date().getTime(); 26 if (now - preTime > delay) { 27 preTime = now; 28 setTimeout(function() { 29 cbFn(); 30 }, delay) 31 } 32 } 33 } 34 35 function cbFn() { 36 divEle.innerHTML = ++count; 37 } 38 </script> 39 </body> 40 </html>