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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| * 节流函数 多次调用方法,按照一定的时间间隔执行 * 当持续触发事件时,保证在一定时间内只调用一次事件处理函数,意思就是说,假设一个用户一直触发这个函数,且每次触发 * 用一句话总结防抖和节流的区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变为每隔一段时间执行 * 实现函数节流我们主要有两种方法:时间戳和定时器 * * @param func 执行函数 * @param wait 间隔时间 * @param options 立即执行 * options 中 leading:false 表示禁用第一次执行 trailing: false 表示禁用停止触发的回调。两者不能共存,否则函数不能执⾏ */ export const throttle = (func, wait = 500, options) => { let timeout let context let args let previous = 0 if (!options) options = { leading: false, trailing: true }
const later = function () { previous = options.leading === false ? 0 : new Date().getTime() timeout = null func.apply(context, args) if (!timeout) context = args = null }
const throttled = function () { const now = new Date().getTime() if (!previous && options.leading === false) previous = now const remaining = wait - (now - previous) context = this args = arguments if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout) timeout = null } previous = now func.apply(context, args) if (!timeout) context = args = null } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining) } } return throttled }
* 在一定时间间隔内,多次调用一个方法,只会执行一次.
* @param {*} func 要进行debouce的函数
* @param {*} wait 等待时间,默认500ms
* @param {*} immediate 是否立即执行
*/
export function debounce(func, wait=500, immediate=false) {
var timeout
return function() {
var context = this
var args = arguments
if (timeout) clearTimeout(timeout)
if (immediate) {
var callNow = !timeout
timeout = setTimeout(function() {
timeout = null
}, wait)
if (callNow) func.apply(context, args)
} else {
timeout = setTimeout(function() {
func.apply(context, args)
}, wait)
}
}
}
|