File tree 1 file changed +23
-33
lines changed
packages/melonjs/src/utils
1 file changed +23
-33
lines changed Original file line number Diff line number Diff line change @@ -25,39 +25,29 @@ export function defer(
25
25
/**
26
26
* returns a function that, when invoked will only be triggered at most once during a given window of time
27
27
* @param fn - the function to be throttled.
28
- * @param delay - the delay in ms
28
+ * @param [wait] - the delay in ms
29
29
* @returns the function that will be throttled
30
30
*/
31
- export const throttle = < R , A extends any [ ] > (
32
- fn : ( ...args : A ) => R ,
33
- delay : number ,
34
- ) : [ ( ...args : A ) => R | undefined , ( ) => void ] => {
35
- let wait = false ;
36
- let timeout : undefined | number ;
37
- let cancelled = false ;
38
-
39
- return [
40
- ( ...args : A ) => {
41
- if ( cancelled ) {
42
- return undefined ;
43
- }
44
- if ( wait ) {
45
- return undefined ;
46
- }
47
-
48
- const val = fn ( ...args ) ;
49
-
50
- wait = true ;
51
-
52
- timeout = window . setTimeout ( ( ) => {
53
- wait = false ;
54
- } , delay ) ;
55
-
56
- return val ;
57
- } ,
58
- ( ) => {
59
- cancelled = true ;
60
- clearTimeout ( timeout ) ;
61
- } ,
62
- ] ;
31
+ export const throttle = ( fn : ( ) => void , wait : number = 100 ) => {
32
+ let inThrottle : boolean ,
33
+ lastFn : ReturnType < typeof setTimeout > ,
34
+ lastTime : number ;
35
+ return ( ...args : [ ] /* empty array */ ) => {
36
+ if ( ! inThrottle ) {
37
+ fn . apply ( this , args ) ;
38
+ lastTime = Date . now ( ) ;
39
+ inThrottle = true ;
40
+ } else {
41
+ clearTimeout ( lastFn ) ;
42
+ lastFn = setTimeout (
43
+ ( ) => {
44
+ if ( Date . now ( ) - lastTime >= wait ) {
45
+ fn . apply ( this , args ) ;
46
+ lastTime = Date . now ( ) ;
47
+ }
48
+ } ,
49
+ Math . max ( wait - ( Date . now ( ) - lastTime ) , 0 ) ,
50
+ ) ;
51
+ }
52
+ } ;
63
53
} ;
You can’t perform that action at this time.
0 commit comments