Martin Tomko Martin Tomko - 1 year ago 158
HTML Question

JavaScript update image every second or less

I have small problem with my javascript.
I have url "" with image (from raspberry pi)
and this image is changing very fast (it is from camera)

so i want to make javascript on website that will change this image every second for example.

my HTML is:

<!DOCTYPE html>
<html lang="en">
<title>Pi Viewer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

img,body {
padding: 0px;
margin: 0px;

<img id="img" src="">
<img id="img1" src="">

<script src="script.js"></script>

and my script:

function update() {
document.getElementById("img").src = "";
document.getElementById("img1").src = "";
setTimeout(update, 1000);
setTimeout(update, 1000);

alert is working bit image is not changing :/ (i have 2 images(they are same))
Thanks for any help.

Answer Source

The problem is that the image src is not altered so the image is not reloaded.

You need to convince the browser that the image is new. A good trick is to append a timestamp to the url so that it is always considered new.

function update() {
    var source = '',
        timestamp = (new Date()).getTime(),
        newUrl = source + '?_=' + timestamp;
    document.getElementById("img").src = newUrl;
    document.getElementById("img1").src =  newUrl;
    setTimeout(update, 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download