p5.js loadImage() ↔ Browser Image Loading: How to Gracefully Cancel or Time‑Out Asynchronous Loads?
26.5K reputation · 16 Feb 2023, 09:35 UTC
p5.js loadImage() ↔ Browser Image Loading
When an image is requested with loadImage(), p5.js internally creates an HTMLImageElement and attaches onload and onerror callbacks. The library offers a timeout argument, but this merely stops the callback from firing after a set period; it does not abort the underlying network request or clear the image source. No public API exists to cancel the load mid‑stream, and developers must resort to manual workarounds such as setting nativeElement.src = '' or using an AbortController with a custom fetch implementation. This lack of a standardized cancellation mechanism is an unresolved decision in the p5.js ecosystem.
Given the growing need for responsive sketches that can abort heavy image loads or enforce strict time limits, the community is debating whether p5.js should expose a cancellable promise or integrate AbortController natively. The current documentation does not cover this scenario, leaving developers uncertain about the best practice.
What are the implications of adding a built‑in abort API to loadImage()?
How can a sketch reliably cancel a pending image load without triggering onload or onerror callbacks?
What would be the most browser‑compatible approach to enforce a timeout that also cancels the underlying request?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
26,525 reputation · 16 Feb 2023, 16:26 UTC
While the token-based approach effectively prevents stale images from updating the sketch, it is important to distinguish between application-level cancellation and network-level abortion. When using loadImage() with a timeout or a token, the JavaScript callback is ignored, but the browser's network thread often continues the download in the background until the resource is fully retrieved or the connection expires.
Resource Considerations
- Connection Limits: Browsers have a finite number of concurrent connections per domain. Multiple "ignored" loads can saturate these slots, delaying subsequent critical requests.
- Memory Overhead: The browser may still allocate memory for the incoming image data before the p5.js wrapper decides to discard it.
For sketches loading high-resolution assets over slow connections, verifying the Network tab in DevTools is essential. If requests remain "Pending" long after your timeout triggers, bypassing loadImage() in favor of fetch() and AbortController is the only way to truly free the network socket.