Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh <img> in jQuery periodically

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.

like image 796
joedborg Avatar asked Sep 07 '11 16:09

joedborg


4 Answers

setInterval(function(){
    $("#myimg").attr("src", "/myimg.jpg?"+new Date().getTime());
},2000);
like image 186
Andy Avatar answered Oct 17 '22 12:10

Andy


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.

like image 42
Simone Gianni Avatar answered Oct 17 '22 12:10

Simone Gianni


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);
like image 3
Joe Avatar answered Oct 17 '22 13:10

Joe


This should do the job:

window.setInterval(function() {
    var d = new Date();
    $("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
}, 2000);
like image 2
Niko Avatar answered Oct 17 '22 11:10

Niko