<!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>Document</title> </head> <body> <input type="text" id="input"> <script> // // 事件节流: 设置一个时间间隔,时间间隔内只允许执行一次如果在这个时间间隔内多次触发,也只执行一次 function throttle(fn, wait) { var context = this let lastTime = 0 return function(...args) { let now = + new Date() // + 将事件格式改为数字型的时间字符串 if((now -lastTime) > wait) { fn.apply(context, args) lastTime = now } } } var input = document.querySelector("#input") input.oninput = throttle(fn,2000) function fn() { console.log(111) } </script> </body> </html>
<!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>Document</title> </head> <body> <button id="btn">asdsad</button> <script> // 防抖函数:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时 function debounce(func, wait) { var timeout return function () { var context = this console.log(this) var args = arguments clearTimeout(timeout) timeout = setTimeout(function() { func.apply(context,args) },wait) } } var btn = document.querySelector("#btn") function fn() { console.log(111) } btn.onclick = debounce(fn,1000) </script> </body> </html>