Image won’t stop flickering on refresh

I’ve looked through and tried many solutions to this issue and nothing has worked. I have an image on a website that needs to be updated 10-30x a second (live video feed) so I have the javascript request the image every 100ms. When the image stays the same, no flickering. When the image changes, I see flickering on the image for 2-3 seconds.

    function initImg() {
        var canvas = document.getElementById("diagimg");
        var context = canvas.getContext("2d");
        img = new Image();
        img.onload = function() {
            var scale = .73;
            canvas.setAttribute("width", 640*scale);
            canvas.setAttribute("height", 480*scale);
            context.scale(scale, scale); //scale it to correct size
            context.drawImage(this, 0, 0);
        img.onerror = function() {
            img.src="images/wait.jpeg"; //if error during loading, display this image
    function refreshImg() {
        img.src = "images/IMAGE.png?time="+new Date().getTime();
        window.setTimeout("refreshImg()", 100);


Fixed the problem – turned out to be that I was trying to write an image at the same time that it was being read.

Quick summary of my setup: websocket connection between website and java program, the image being loaded onto the webpage is constantly being overwritten by an external program.

The fix was to have the website request the websocket server to copy the image. The server (java program) copies the image, checks if the copy is equal to the original, and sends a message to the website that the image is ready to be read. The device ID is also appended to the filepath so that each connected device (each instance of the website open) has its own image that will only be changed when it requests an update (it requests a new image once it’s done loading).

This means that images are only overwritten when the client requests them, and the client only reads them when the java websocket says that it’s done being copied.

I’m sure it’s inefficient but it only needs to refresh at 10hz and the entire process only takes about 10ms on its own thread, so doesn’t really matter.