I have an event listener that doesn't fire if the startCall
function is running.
The startCall
function has a setInterval
that calls 30 times per second.
I figured that the setInterval
was blocking the event listener, so I decreased the number of times it calls, but the event listener still didn't fire.
It only works if I remove the startCall
function. Why is this the case?
Here is the event listener:
document.querySelector(".allowUserButton").addEventListener("click", function () {
const allowUserEmail = document.querySelector(".allowUser").value;
const allowUserMessage = document.querySelector(".allowUserMessage");
if (!allowUserEmail) {
allowUserMessage.innerHTML = "Fill in the Allow User field.";
return;
};
if (!validateEmail(allowUserEmail)) {
allowUserMessage.innerHTML = "Invalid Email format.";
return;
};
allowUserMessage.innerHTML = "Loading...";
fetch(`/allowUserToCall/${uuid}/${allowUserEmail}`)
.then(res => res.json())
.then(data => {
const message4 = data.message;
allowUserMessage.innerHTML = message4;
});
});
//startCall();
Here is the startCall
method:
function startCall() {
const canvasClass = `c${Math.round(Math.random() * 9007199254740991)}`
const webcamTags = `
<canvas class="${canvasClass}"></canvas>
<video style="display: none;" autoplay></video>
`;
document.body.innerHTML += webcamTags;
const webcamErrorMessage = "Can't access webcam.";
const sampleFps = 30;
let video, canvas, ctx;
if (navigator.getUserMedia) {
navigator.getUserMedia({
video: true,
audio: false
}, function (localWebcamStream) {
video = document.querySelector("video");
video.srcObject = localWebcamStream;
canvas = document.querySelector(`.${canvasClass}`);
ctx = canvas.getContext("2d");
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const isPhone = windowHeight / windowWidth;
let canvasDimension;
if (isPhone) {
canvasDimension = windowWidth / 4;
} else {
canvasDimension = windowWidth / 6;
};
canvas.width = canvasDimension;
canvas.height = canvasDimension;
setInterval(() => {
ctx.drawImage(video, 0, 0, canvasDimension, canvasDimension);
const imageData = ctx.getImageData(0, 0, canvasDimension, canvasDimension);
const buffer = imageData.data.buffer;
socket.emit("webcamSnapshot", buffer);
}, 1000 / sampleFps);
socket.on("incomingWebcamSnapshot", function (bufferDetails) {
const {buffer, email} = bufferDetails;
console.log(buffer, email);
});
}, function () {
message.innerHTML = webcamErrorMessage;
});
} else {
message.innerHTML = webcamErrorMessage;
};
};