<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>防抖</title> </head> <body> <input type="text" /> <input type="submit" id="input" /> <script type="text/javascript"> let btn = document.getElementById('input') btn.addEventListener('click',debounce(submit,5000),false) function submit(arg){ console.log(this) console.log(arg) } function debounce(fn,time){ let t = null; return function(){ // 第一次执行 if(t===null){ fn.apply(this,arguments) } // 非第一次 else { clearTimeout(t) } t = setTimeout(() =>{ t = null },time) } } </script> </body> </html>
效果图: