10

Similar to How to reload/refresh an element(image) in jQuery but not at the same time.

I have a webcam that saves images every 2 seconds rather than streaming. Using jQuery (or straight JS) I want to refresh just the image element.

Should be easy, but all my searches show the refresh on request.

Community
  • 1
  • 1
joedborg
  • 17,651
  • 32
  • 84
  • 118

5 Answers5

15
setInterval(function(){
    $("#myimg").attr("src", "/myimg.jpg?"+new Date().getTime());
},2000);
Andy
  • 29,707
  • 9
  • 41
  • 58
  • Where you have "myimg.jpg" I have a JS global var set with the path, how do I integrate that? I've tried $("#myimg").attr("src", imagePath+"?"+d.getTime()); but the image disappears – joedborg Sep 07 '11 at 16:26
  • i wrote `new Date().getTime()`. if you use `d.getTime()` you'll have to first assign it `var d = new Date();` – Andy Sep 07 '11 at 16:28
3

setInterval is a timer that will execute a function everything x milliseconds

setInterval(function () {
    var d = new Date();
    $("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
}, 2000);
Joe
  • 80,724
  • 18
  • 127
  • 145
  • Where you have "myimg.jpg" I have a JS global var set with the path, how do I integrate that? I've tried $("#myimg").attr("src", imagePath+"?"+d.getTime()); but the image disappears – joedborg Sep 07 '11 at 16:26
3

You must force the browser to realod the image instead of taking it from cache. You can do it by changing the url, adding a useless parameter that changes each time, for example a timestamp.

$('img.webcam').each(function() {
    var jqt = $(this);
    var src = jqt.attr('src');
    src = src.substr(0,src.indexOf('?'));
    src += '?_ts=' + new Date().getTime();
    jqt.attr('src',src);
});

Execute this snippet inside a timer or on a click or both or whatever.

Simone Gianni
  • 11,426
  • 40
  • 49
2

This should do the job:

window.setInterval(function() {
    var d = new Date();
    $("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
}, 2000);
Niko
  • 26,516
  • 9
  • 93
  • 110
  • Where you have "myimg.jpg" I have a JS global var set with the path, how do I integrate that? I've tried $("#myimg").attr("src", imagePath+"?"+d.getTime()); but the image disappears – joedborg Sep 07 '11 at 16:26
1

Add a timestamp to the image source it will refresh.

setInterval(function(){
    $("img").each(function(){
       var timeStamp = (new Date()).getTime();
       $(this).attr("src", $(this).attr("src") + timeStamp );
    });
}, 2000);
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • Unlike the other answers this would increase the size of the URL every 2 seconds (because you keep appending, not replacing). It wouldn't take too long before you had a URL thousands of characters long. – Arbiter Jul 03 '13 at 20:31