Exercise 3: What the if (!currentStream) return Check Guards Against — Possible Solution ==================================================================== WHY scan() KEEPS GETTING CALLED ------------------------------ When no barcode is detected in a frame, the scan function calls requestAnimationFrame(scan), scheduling itself to run again on the next frame. This creates an ongoing loop that keeps calling scan() repeatedly, frame after frame, for as long as nothing gets detected. WHAT THE CHECK GUARDS AGAINST ------------------------------ stopScanner() sets currentStream to null and stops the underlying camera tracks, but it has no way to reach into and cancel an already-scheduled requestAnimationFrame callback that's still pending from before stopScanner() ran. Without the if (!currentStream) return; check, that already-scheduled scan() call would still execute one more time even after the camera was supposedly stopped - trying to detect barcodes against a video element whose stream no longer exists or is already closed. WHY THIS IS NECESSARY GIVEN THE requestAnimationFrame LOOP ------------------------------ Because each scan() call schedules the next one before checking whether it should still be running, there's always at least one more scheduled call already in flight by the time stopScanner() executes. The check at the top of scan() is what actually stops that lingering call from doing any real work or scheduling yet another one - without it, the loop could keep calling scan() detection logic even after the developer's own code believes scanning has fully stopped. WHY THIS WORKS AS AN ANSWER ------------------------------ It correctly explains why scan() keeps re-scheduling itself via requestAnimationFrame, and correctly explains that the check exists specifically because stopScanner() cannot cancel an already-pending scheduled call - the check is what actually makes that lingering call a safe no-op instead of continuing to run.