There are two immediate issues here:
- You're trying to re-request an image at the same URL, which won't prompt a reload.
- You're using a
while(true)
loop without no exit condition.
I'd be surprised if the code you provided wasn't freezing your website. A while(true)
loop will run thousands of times per second. Within 30 seconds, the browser will choke and either crash the tab or lock up the browser entirely.
What you're more likely looking for, instead of a while loop, is some sort of cache-busting mechanism.
Timestamp
The simplest way to fix this would be to set up your web browser to serve the image at a static URL, then update the URL on your client with the current timestamp tacked onto the end as a query parameter. For instance,
const elem = document.getElementById('img');
const url = "/static/image_request.png";
setInterval(function(){
// e.g., static/image_request.png?r=1566576298288
elem.setAttribute('src', `${url}?r=${new Date().getTime()}`);
}, 10000);
With this code, every ten seconds, the browser will update the URL with a new timestamp on the end; this should prompt the image to reload. If you've set up your server correctly, the query parameters won't affect where you look for the file, and it should return the content of the static URL.
As an aside, you really shouldn't do this frequently, as it will likely cause the image to disappear briefly while it is being loaded. For periodic refreshes, though, it should work fine.
Websockets
You might find the above solution perfectly workable for your needs, but I do want to briefly elaborate on a better, but more involved, solution.
Instead of hard-coding the image path, you could use WebSockets to open a persistent connection between the client and the server. Each time an image changes on the server, it could broadcast the encoded content of the image to all clients through the socket connection.
When a client receives a socket message from the server, it could update the URL of the image with the encoded content directly, without having to make another request to the server.
This method would save you from having to deal with reloading one persistent file path, and also eliminate any flashing or vanishing when the image is reloaded. This method would also allow you to switch from using an img
tag to a canvas
, which might be better depending on your exact needs.