Categories
General

Auto-update an image every X seconds

For a web cam site I’m working on, I wanted to automatically update the web cam image every so often. The classic way to do this is with meta refresh, but that’s supposedly deprecated and it unnecessarily reloads the entire page. JavaScript to the rescue! This little snippet reloads any image with the “refresh” ID every 60 seconds. It’s mostly borrowed from here, with the setInterval thing added because I didn’t like the onload thing in the body tag.

function cambox_refresh() {
echo "n" . '<script type="text/javascript">// <![CDATA[
function refreshCam() {
image = document.getElementById("refresh");
image.src = image.src + "?rand=" + Math.random();
}                 setInterval("refreshCam()", 60000);
// ]]></script>'. "n";
}
add_action('wp_footer', 'cambox_refresh');