1- /* @flow strict */
2-
3- type ThrottleOptions = { |
4- start ? : boolean ,
5- middle ? : boolean ,
1+ export interface ThrottleOptions {
2+ /**
3+ * Fire immediately on the first call.
4+ */
5+ start ?: boolean
6+ /**
7+ * Fire as soon as `wait` has passed.
8+ */
9+ middle ?: boolean
10+ /**
11+ * Cancel after the first successful call.
12+ */
613 once ?: boolean
7- | }
8- export function throttle < T : $ReadOnlyArray < mixed >> (
9- callback : ( ...T ) = > mixed ,
10- wait : number = 0 ,
14+ }
15+
16+ interface Throttler < T extends unknown [ ] > {
17+ ( ...args : T ) : void
18+ cancel ( ) : void
19+ }
20+
21+ export function throttle < T extends unknown [ ] > (
22+ callback : ( ...args : T ) => unknown ,
23+ wait = 0 ,
1124 { start = true , middle = true , once = false } : ThrottleOptions = { }
12- ) : ( ... T ) = > void {
25+ ) : Throttler < T > {
1326 let last = 0
14- let timer
27+ let timer : number | undefined
1528 let cancelled = false
16- const fn = ( ...args ) => {
29+ function fn ( this : unknown , ...args : T ) {
1730 if ( cancelled ) return
1831 const delta = Date . now ( ) - last
1932 last = Date . now ( )
2033 if ( start ) {
21- //eslint-disable-next-line flowtype/no-flow-fix-me-comments
22- // $FlowFixMe this isn't a const
2334 start = false
24- callback ( ... args )
35+ callback . apply ( this , args )
2536 if ( once ) fn . cancel ( )
2637 } else if ( ( middle && delta < wait ) || ! middle ) {
2738 clearTimeout ( timer )
2839 timer = setTimeout (
2940 ( ) => {
3041 last = Date . now ( )
31- callback ( ... args )
42+ callback . apply ( this , args )
3243 if ( once ) fn . cancel ( )
3344 } ,
3445 ! middle ? wait : wait - delta
@@ -42,10 +53,10 @@ export function throttle<T: $ReadOnlyArray<mixed>>(
4253 return fn
4354}
4455
45- export function debounce < T : $ReadOnlyArray < mixed > >(
46- callback : ( ...T ) => mixed ,
47- wait : number = 0 ,
56+ export function debounce < T extends unknown [ ] > (
57+ callback : ( ...args : T ) => unknown ,
58+ wait = 0 ,
4859 { start = false , middle = false , once = false } : ThrottleOptions = { }
49- ) : ( ... T ) => void {
60+ ) : Throttler < T > {
5061 return throttle ( callback , wait , { start, middle, once} )
5162}
0 commit comments