关于防抖debounce和节流throttle

tech2025-05-27  4

最近又用到了防抖和节流这两个方法,平时都是直接调用的方法 也没太注意实现的原理 今天就好好的了解一下!!

首先防抖 中有三个类型 分别是 规定时间内点击最后一次结束时才触发、点击第一次就触发,规定时间内不再触发、以及根据传入是否立即执行来进行触发,

首先是非立即执行的版本

function debounce(fn,time){ let time = time || 500; let timeout; return function(){ let that = this; let arg = arguments; if(timeout){ clearTimeout(timeout) } timeout = setTimeout(()=>{ timeout = null; fn.apply(that,arg) }) } }

其次是立即执行的版本

function debounce(fn,time){ let time = time || 500; let timeout; return function(){ let that = this; let arg = arguments; if(timeout){ clearTimeout(timeout) } let callNow = !timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(that, arg) } }

然后是最终版本的代码

// 防抖 /** * @desc 函数防抖 * @param fn 函数 * @param time延迟执行毫秒数 * @param immediately true 表立即执行,false 表非立即执行 */ function debounce(fn,time,immediately){ let time = time || 500; let timeout; return function(){ let that = this; let arg = arguments; if(timeout){clearTimeout(timeout)} if(immediately){ let now = !timeout; timeout = setTimeout(()=>{ timeout = null; },time) if(now){fn.apply(that,arg)} }else{ timeout = setTimeout(()=>{ timeout = null; fn.apply(that,arg) },time) } } }

下面讲的是节流

节流(throttle)

所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。

对于节流,一般有两种方式可以实现,分别是时间戳版和定时器版。

时间戳版:

function throttle(func, wait) { let previous = 0; return function() { let now = Date.now(); let context = this; let args = arguments; if (now - previous > wait) { func.apply(context, args); previous = now; } } }

定时器版:

 

function throttle(func, wait) { let timeout; return function() { let context = this; let args = arguments; if (!timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } }

双剑合璧版:

 

/** * @desc 函数节流 * @param func 函数 * @param wait 延迟执行毫秒数 * @param type 1 表时间戳版,2 表定时器版 */ function throttle(func, wait ,type) { let previous,timeout; if(type===1){ previous = 0; }else if(type===2){ timeout; } return function() { let context = this; let args = arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }else if(type===2){ if (!timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } } }

 

最新回复(0)