Reload <img> element from same source

I have an image at the URL (from a Raspberry Pi) and this image is changing very fast (it is from a camera).

So I want to have some JavaScript on a website that will reload 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, but the image is not changing :/ (I have 2 images (they are the same))



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);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.