1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>防抖节流</title> <style> #container{ height: 200px; width: 100%; background: rebeccapurple; text-align: center; font-size: 30px; color: #fff; } </style> </head> <body> <div id="container"></div> <script> const container = document.getElementById("container"); function debounce(fn,wait,immediate){ let timer; return function(event){ clearTimeout(timer); let _this = this; if(immediate){ let isCall = !timer; timer = setTimeout(function(){ timer = null; },wait); if(isCall){ fn.apply(_this,[event]); } }else{ timer = setTimeout(function(){ fn.apply(_this,[event]) },wait); } } } function show(e){ this.innerHTML = e.clientX; } container.onmousemove = debounce(show,1000,false); </script> </body> </html>
|