Skip to content

Commit b785627

Browse files
committed
fix: race condition
Fix race condition when render/clear is called in rapid succession. This issue was first spotted when trying to use this library in react: Relevant issue : briosheje/react-html5-qrcode-reader#2
1 parent 4a9a039 commit b785627

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/html5-qrcode-scanner.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ export class Html5QrcodeScanner {
178178
private persistedDataManager: PersistedDataManager;
179179
private scanTypeSelector: ScanTypeSelector;
180180
private logger: Logger;
181+
private isCleared = false;
181182

182183
// Initally null fields.
183184
private html5Qrcode: Html5Qrcode | undefined;
@@ -232,6 +233,7 @@ export class Html5QrcodeScanner {
232233
public render(
233234
qrCodeSuccessCallback: QrcodeSuccessCallback,
234235
qrCodeErrorCallback: QrcodeErrorCallback | undefined) {
236+
this.isCleared = false;
235237
this.lastMatchFound = null;
236238

237239
// Add wrapper to success callback.
@@ -324,6 +326,8 @@ export class Html5QrcodeScanner {
324326
* fails otherwise.
325327
*/
326328
public clear(): Promise<void> {
329+
this.isCleared = true;
330+
327331
const emptyHtmlContainer = () => {
328332
const mainContainer = document.getElementById(this.elementId);
329333
if (mainContainer) {
@@ -546,6 +550,9 @@ export class Html5QrcodeScanner {
546550
}
547551

548552
Html5Qrcode.getCameras().then((cameras) => {
553+
if ($this.isCleared) {
554+
return;
555+
}
549556
// By this point the user has granted camera permissions.
550557
$this.persistedDataManager.setHasPermission(
551558
/* hasPermission */ true);
@@ -612,6 +619,9 @@ export class Html5QrcodeScanner {
612619
&& this.persistedDataManager.hasCameraPermissions()) {
613620
CameraPermissions.hasPermissions().then(
614621
(hasPermissions: boolean) => {
622+
if ($this.isCleared) {
623+
return;
624+
}
615625
if (hasPermissions) {
616626
$this.createCameraListUi(
617627
scpCameraScanRegion, requestPermissionContainer);
@@ -964,6 +974,9 @@ export class Html5QrcodeScanner {
964974
CameraPermissions.hasPermissions().then(
965975
(hasPermissions: boolean) => {
966976
if (hasPermissions) {
977+
if ($this.isCleared) {
978+
return;
979+
}
967980
// Start feed.
968981
// Assuming at this point the permission button exists.
969982
let permissionButton = document.getElementById(

0 commit comments

Comments
 (0)