|
|
@@ -79,42 +79,34 @@ export function formatTime (time, option) {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
-export function debounce (fn, wait, immediate) {
|
|
|
- let timeout, context, args, timestamp
|
|
|
+export function debounce (func, wait, immediate) {
|
|
|
+ let timeout, context, args
|
|
|
|
|
|
const later = function () {
|
|
|
- // 据上一次触发时间间隔
|
|
|
- const last = Date.now() - timestamp
|
|
|
-
|
|
|
- // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
|
|
|
- if (last < wait) {
|
|
|
- timeout = setTimeout(later, wait - last)
|
|
|
- } else {
|
|
|
- if (!immediate) {
|
|
|
- fn.apply(context, args)
|
|
|
- }
|
|
|
- timeout = context = args = null
|
|
|
+ if (!immediate) {
|
|
|
+ func.apply(context, args)
|
|
|
}
|
|
|
+ timeout = context = args = null
|
|
|
}
|
|
|
|
|
|
return function (...params) {
|
|
|
- timestamp = Date.now()
|
|
|
context = this
|
|
|
args = params
|
|
|
- // 如果延时不存在,重新设定延时
|
|
|
- if (!timeout) {
|
|
|
- timeout = setTimeout(later, wait)
|
|
|
- if (immediate) {
|
|
|
- fn.apply(context, args)
|
|
|
- context = params = null
|
|
|
- }
|
|
|
+ if (timeout) {
|
|
|
+ clearTimeout(timeout)
|
|
|
+ } else if (immediate) {
|
|
|
+ func.apply(context, args)
|
|
|
+ context = args = null
|
|
|
}
|
|
|
+ timeout = setTimeout(later, wait)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+// leading-true,trailing-true:默认情况,间隔到了立即执行且保留尾调用
|
|
|
+// leading-true,trailing-false:去除尾调用
|
|
|
+// leading-false, trailing-true:在间隔结束时执行函数
|
|
|
export function throttle (func, wait, options) {
|
|
|
let timeout, context, args
|
|
|
-
|
|
|
// 上一次执行回调的时间戳
|
|
|
let previous = 0
|
|
|
|
|
|
@@ -128,10 +120,7 @@ export function throttle (func, wait, options) {
|
|
|
// 每次触发回调函数后设置 previous 为 0
|
|
|
// 不然为当前时间
|
|
|
previous = options.leading === false ? 0 : Date.now()
|
|
|
-
|
|
|
- // 执行函数
|
|
|
func.apply(context, args)
|
|
|
-
|
|
|
timeout = context = args = null
|
|
|
}
|
|
|
|
|
|
@@ -154,16 +143,9 @@ export function throttle (func, wait, options) {
|
|
|
context = this
|
|
|
args = params
|
|
|
|
|
|
- // 要么是到了间隔时间了,随即触发方法(remaining <= 0)
|
|
|
- // 要么是没有传入 {leading: false},且第一次触发回调,即立即触发
|
|
|
- // 此时 previous 为 0,wait - (now - previous) 也满足 <= 0
|
|
|
- // 之后便会把 previous 值迅速置为 now
|
|
|
- if (remaining <= 0 || remaining > wait) {
|
|
|
+ if (remaining <= 0) {
|
|
|
if (timeout) {
|
|
|
clearTimeout(timeout)
|
|
|
-
|
|
|
- // clearTimeout(timeout) 并不会把 timeout 设为 null
|
|
|
- // 手动设置,便于后续判断
|
|
|
timeout = null
|
|
|
}
|
|
|
|
|
|
@@ -172,9 +154,7 @@ export function throttle (func, wait, options) {
|
|
|
|
|
|
// 执行 func 函数
|
|
|
func.apply(context, args)
|
|
|
- if (!timeout) {
|
|
|
- context = args = null
|
|
|
- }
|
|
|
+ context = args = null
|
|
|
} else if (!timeout && options.trailing !== false) {
|
|
|
// 最后一次需要触发的情况
|
|
|
// 如果已经存在一个定时器,则不会进入该 if 分支
|