手寫封裝防抖debounce
阿新 • • 發佈:2021-11-04
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>封裝防抖debounce</title> </head> <body> <input type="text" id="input1"> </body> </html> <script type="text/javascript"> // 封裝防抖 function那時候我只有一臺錄音機也沒有電腦 也不敢奢求說唱會讓自己的生活變好debounce(fn, delay = 500) { //timer 是閉包中的 let timer = null return function () { if(timer) { clearTimeout(timer) } timer = setTimeout(() => { fn.apply(this, arguments) timer = null },delay) } } const input1= document.getElementById('input1') input1.addEventListener('keyup', debounce(function () { console.log(input1.value) }),600) </script>