Home > Uncategorized > Constantly refresh image with Javascript

Constantly refresh image with Javascript

A simple way to refresh an image in Javascript is to use a setTimeout or setInterval, however, it doesn’t take into account how long it takes to load the image, so you could end up with a situation where a user on a slow connection does not load the image in time before the next image is requested.

Binding the load event to a image element with JQuery tends to fire prematurely, so that it does not give a fair reflection on when this image is loaded.

Here is my solution (tested in Google Chrome):

<html>
<script src=”http://code.jquery.com/jquery-1.9.1.min.js”></script&gt;
<script language=”javascript”>
$(init)
function init() {
refresh();
}
function refresh() {
var strImageUrl = “http://image.captchas.net?client=demo&random=RandomZufall&&#8221; + Date.now();
var img = new Image();
img.onload = function() {
$(“#img”).attr(‘src’,strImageUrl);
refresh();
}
img.src = strImageUrl;
}
</script>
<img id=”img”>
</html>

 

 

Advertisements
Categories: Uncategorized
  1. TheUberOverLord
    March 29, 2014 at 4:23 pm

    This does what you want using one line of HTML and includes error recovery and there is a working demo shown here:

    http://foscam.us/forum/a-how-to-embed-any-foscam-ip-camera-in-webpage-using-1-line-t9113.html#p43654

    Don

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: