函数防抖和节流
一、函数防抖
函数防抖:事件在n秒后再执行,也就是延迟执行,若n秒内再次触发事件,则重新开始计时。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
function debounce (fn, delay) { var t = null return function () { var _self = this, args = arguments
if (t) { clearTimeout(t) }
t = setTimeout(() => { fn.apply(_self, args) }, delay) } }
|
首次触发不防抖,n秒之内触发防抖。应用于频繁AJAX请求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
function debounce (fn, delay, triggerNow = false) { var t = null, res = null
var _debounce = function () { var _self = this, args = arguments
if (t) { clearTimeout(t) }
if (triggerNow) { var exec = !t t = setTimeout(() => { t = null }, delay) if (exec) { res = fn.apply(_self, args) } } else { t = setTimeout(() => { res = fn.apply(_self, args) }, delay) } return res }
_debounce.remove = function () { clearTimeout(t) t = null res = null }
return _debounce }
|
二、函数节流
函数节流:事件在n秒之内只执行一次。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
function throttle (fn, delay){ var lock = false return function(){ var _self = this, args = arguments if(lock) { return } fn.apply(_self,args) lock = true setTimeout(()=>{ lock = false }, delay) } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
function throttle (fn, delay) { var t = null, begin = new Date().getTime()
return function () { var _self = this, args = arguments, cur = new Date().getTime()
if (t) { clearTimeout(t) }
if (cur - begin >= delay) { fn.apply(_self, args) begin = cur } else { t = setTimeout(() => { fn.apply(_self, args) }, delay) } } }
|