节流与防抖
节流
throttle节流:减少请求资源,比如mouseove或resize事件会重复触发,使用throttle可以减少事件触发次数。实现原理是,在一段时间内只能完成固定次数请求,比如去火车站安检,一次只能过几个人,后边进行排队,避免前面发生拥挤。
// 事件戳方法function throttle(callback, wait) {let pre = Date.now();return function () {let now = Date.now();if (now - pre >= wait) {fn.apply(this, arguments);pre = Date.now();}};}function handle() {console.log(Math.random());}window.addEventListener("mouseover", throttle(handle, 1000))
// 定时器方法function throttle(callback, wait) {let timer = null;return function () {if (!timer) {timer = setTimeout(function () {callback.apply(this, arguments);timer = null;}, wait);}};}function handle() {console.log(Math.random());}window.addEventListener("mouseover", throttle(handle, 1000));
防抖
debounce防抖:防抖是过了多久后才会执行的事件。 常见的input输入,根据输入数据发送接口请求【匹配相似关键词】。由于在输入过程中会有停顿,不确定什么时候输入完成,需要通过防抖机制,【输入词停顿300毫秒后表示输入完成,发送模糊接口请求】。 现实生活中的坐电梯时,电梯关门会一直等最后一个人进入停顿一段时间后才关门。
防抖分为非立即执行函数和立即执行函数
非立即执行函数:函数触发后不会立即执行,要等防抖设置的时间后才执行。等电梯的过程是非立即执行。
非立即执行版的意思是触发事件后函数不会立即执行,而是在 n 秒后执行,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
function debounce(callback, wait) {let timeout = null;return function () {if (timeout) clearTimeout(timeout);timeout = setTimeout(() => {callback.apply(this, arguments);}, wait);};}function handle() {console.log(Math.random());}window.addEventListener("mouseover", debounce(handle, 1000));
- 立即执行:先执行一次,输入框中有一个值时可以先立即执行下接口请求。触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果。
function debounce(callback, wait){let timeout = null;return function(){if(timeout) clearTimeout(timeout);let runEvent = !timeout;timeout = setTimeout(()=>{timeout = null;}, wait)if(runEvent) callback.apply(this, arguments)};}function handle() {console.log(Math.random());}window.addEventListener("mouseover", debounce(handle, 1000));
