forked from getcursor/cursor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
componentUtils.ts
43 lines (42 loc) · 1.27 KB
/
componentUtils.ts
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
export function throttleCallback(fn: Function, limit = 300) {
let inThrottle: boolean,
lastFn: ReturnType<typeof setTimeout>,
lastTime: number
return function (this: any) {
const context = this,
args = arguments
if (!inThrottle) {
fn.apply(context, args)
lastTime = Date.now()
inThrottle = true
} else {
clearTimeout(lastFn)
lastFn = setTimeout(() => {
if (Date.now() - lastTime >= limit) {
fn.apply(context, args)
lastTime = Date.now()
inThrottle = false
}
}, Math.max(limit - (Date.now() - lastTime), 0))
}
}
}
export function normalThrottleCallback(fn: Function, limit = 300) {
let inThrottle: boolean,
lastFn: ReturnType<typeof setTimeout>,
lastTime: number
return function (...args: any[]) {
if (!inThrottle) {
fn(args)
lastTime = Date.now()
inThrottle = true
} else {
clearTimeout(lastFn)
lastFn = setTimeout(() => {
fn(args)
lastTime = Date.now()
inThrottle = false
}, limit)
}
}
}