Skip to content

Commit 12b7612

Browse files
authored
Fix canplay listener and interval accumulation in doUseCamera() (sugarlabs#5837)
* Fix canplay listener and interval accumulation in doUseCamera() * Reset CameraManager.intervalId to null after clearInterval
1 parent fbb3afb commit 12b7612

File tree

1 file changed

+35
-19
lines changed

1 file changed

+35
-19
lines changed

js/utils/utils.js

Lines changed: 35 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1072,6 +1072,8 @@ let prepareMacroExports = (name, stack, macroDict) => {
10721072
// Encapsulates camera-related operations for video/image capture
10731073
const CameraManager = {
10741074
isSetup: false,
1075+
canPlayHandler: null,
1076+
intervalId: null,
10751077

10761078
/**
10771079
* Resets the camera setup state
@@ -1129,34 +1131,48 @@ let doUseCamera = (args, turtles, turtle, isVideo, cameraID, setCameraID, errorM
11291131
streaming = true;
11301132
video.play();
11311133
if (isVideo) {
1134+
if (CameraManager.intervalId !== null) {
1135+
window.clearInterval(CameraManager.intervalId);
1136+
CameraManager.intervalId = null;
1137+
}
11321138
cameraID = window.setInterval(draw, 100);
1139+
CameraManager.intervalId = cameraID;
11331140
setCameraID(cameraID);
11341141
} else {
11351142
draw();
11361143
}
11371144
}
11381145

1139-
video.addEventListener(
1140-
"canplay",
1141-
() => {
1142-
// console.debug("canplay", streaming, CameraManager.isSetup);
1143-
if (!streaming) {
1144-
video.setAttribute("width", w);
1145-
video.setAttribute("height", h);
1146-
canvas.setAttribute("width", w);
1147-
canvas.setAttribute("height", h);
1148-
streaming = true;
1149-
1150-
if (isVideo) {
1151-
cameraID = window.setInterval(draw, 100);
1152-
setCameraID(cameraID);
1153-
} else {
1154-
draw();
1146+
if (CameraManager.canPlayHandler) {
1147+
video.removeEventListener("canplay", CameraManager.canPlayHandler, false);
1148+
}
1149+
1150+
function handleCanPlay() {
1151+
// console.debug("canplay", streaming, CameraManager.isSetup);
1152+
if (!streaming) {
1153+
video.setAttribute("width", w);
1154+
video.setAttribute("height", h);
1155+
canvas.setAttribute("width", w);
1156+
canvas.setAttribute("height", h);
1157+
streaming = true;
1158+
1159+
if (isVideo) {
1160+
if (CameraManager.intervalId !== null) {
1161+
window.clearInterval(CameraManager.intervalId);
1162+
CameraManager.intervalId = null;
11551163
}
1164+
cameraID = window.setInterval(draw, 100);
1165+
CameraManager.intervalId = cameraID;
1166+
setCameraID(cameraID);
1167+
} else {
1168+
draw();
11561169
}
1157-
},
1158-
false
1159-
);
1170+
}
1171+
}
1172+
1173+
CameraManager.canPlayHandler = handleCanPlay;
1174+
1175+
video.addEventListener("canplay", CameraManager.canPlayHandler, false);
11601176
};
11611177

11621178
/**

0 commit comments

Comments
 (0)