Skip to content

Commit d2e2f3f

Browse files
committed
fix a regression with window resizing not triggering a canvas and viewport resize
1 parent 4b80f88 commit d2e2f3f

File tree

1 file changed

+23
-33
lines changed

1 file changed

+23
-33
lines changed

packages/melonjs/src/utils/function.ts

+23-33
Original file line numberDiff line numberDiff line change
@@ -25,39 +25,29 @@ export function defer(
2525
/**
2626
* returns a function that, when invoked will only be triggered at most once during a given window of time
2727
* @param fn - the function to be throttled.
28-
* @param delay - the delay in ms
28+
* @param [wait] - the delay in ms
2929
* @returns the function that will be throttled
3030
*/
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+
};
6353
};

0 commit comments

Comments
 (0)