防抖(debounce)
所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
完整代码
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body><button id="btn">按钮</button><script>// 只针对最后一次输入触发var timervar btn = document.getElementById("btn");btn.onclick = function(){// if(timer){// clearTimeout(timer)// }// timer = setTimeout(function(){// console.log(1)// },1000)debounce(()=>{console.log(1)},1000)}function debounce(fn,time){if(timer){clearTimeout(timer)}timer = setTimeout(fn,time)}</script></body></html>

ps:
节流(throttle)
所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。
