Skip to content

Commit 05af8a0

Browse files
committed
fix: add throttle
1 parent b364f42 commit 05af8a0

1 file changed

Lines changed: 26 additions & 11 deletions

File tree

packages/pluggableWidgets/barcode-scanner-native/src/BarcodeScanner.tsx

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,21 @@ export function BarcodeScanner(props: Props): ReactElement {
1616

1717
const styles = useMemo(() => flattenStyles(defaultBarcodeScannerStyle, props.style), [props.style]);
1818

19+
const onCodeScanned = (codes: Code[]) => {
20+
if (props.barcode.status !== ValueStatus.Available || codes.length === 0 || !codes[0].value) {
21+
return;
22+
}
23+
const { value } = codes[0];
24+
25+
if (value !== props.barcode.value) {
26+
props.barcode.setValue(value);
27+
}
28+
executeAction(props.onDetect);
29+
};
30+
1931
const codeScanner = useCodeScanner({
2032
codeTypes: ["ean-13", "qr", "aztec", "codabar", "code-128", "data-matrix"],
21-
onCodeScanned: (codes: Code[]) => {
22-
if (props.barcode.status !== ValueStatus.Available || codes.length === 0 || !codes[0].value) {
23-
return;
24-
}
25-
const { value } = codes[0];
26-
27-
if (value !== props.barcode.value) {
28-
props.barcode.setValue(value);
29-
}
30-
executeAction(props.onDetect);
31-
}
33+
onCodeScanned: throttle(onCodeScanned, 2000)
3234
});
3335

3436
return (
@@ -56,3 +58,16 @@ export function BarcodeScanner(props: Props): ReactElement {
5658
</View>
5759
);
5860
}
61+
62+
export function throttle<F extends (...params: any[]) => void>(fn: F, threshold: number): F {
63+
let wait = false;
64+
return function invokeFn(this: any, ...args: any[]) {
65+
if (!wait) {
66+
fn(...args);
67+
wait = true;
68+
setTimeout(() => {
69+
wait = false;
70+
}, threshold);
71+
}
72+
} as F;
73+
}

0 commit comments

Comments
 (0)