2

I am putting together a jquery mobile site that includes several separate pages (*.htm) for webcams. On those page, I am loading a set interval function that refreshes the image grab from the camera every few seconds and simulates video.

The problem occurs however when I navigate away from the webcam page (webcam.htm) using a nav link or back button back to index.htm, the webcam.htm page remains in the DOM and keeps pulling the images every few seconds.

How can I clear the page or at least endinterval when the user leaves?

<script type="text/javascript">
    function camfresh() {
        setInterval(function(){ $("#rmcam").attr("src", "image.jpg?"+new Date().getTime());},2000);
    }
</script>
Jasper
  • 74,169
  • 13
  • 144
  • 142
edvan22
  • 77
  • 1
  • 7
  • A quick-and-dirty solution, if you don't want to mess up with listeners, could be to clear the interval inside the interval if a certain condition happens (in this case if the page is not visible anymore. For visibility question see http://stackoverflow.com/questions/178325/testing-if-something-is-hidden-with-jquery). – reallynice Nov 28 '13 at 12:39

1 Answers1

2

You can use the pageshow and pagehide events to start and stop the interval:

var myInterval;
$(document).delegate('.ui-page', 'pageshow', function () {

    //note that `this` refers to the current `data-role="page"` element

    //cache `this` for later (inside the setInterval anonymous function)
    var $this = $(this);

    myInterval = setInterval(function(){
        $this.find("#rmcam").attr("src", "image.jpg?"+new Date().getTime());
    }, 2000);
}).delegate('.ui-page', 'pagehide', function () {
    clearInterval(myInterval);
});

You can change the .ui-page selectors to be more specific (currently they will select every pseudo-page).

Jasper
  • 74,169
  • 13
  • 144
  • 142
  • Thanks for the assistance, looks like the interval is loading and firing but I am getting TypeError: $this.find is not a function [Break On This Error] $this.find("#rvcam").attr("src", "image.jpg?"+new Date().getTime()); #webcams (line 19) TypeError: $this.find is not a function [Break On This Error] $this.find("#rvcam").attr("src", "image.jpg?"+new Date().getTime()); Any ideas? – edvan22 Aug 09 '12 at 09:44
  • Yeah, `.find()` is a method that has to be run on a jQuery object since it's a jQuery function. I only cached `this` rather than `$(this)`. I edited the question with this fix. – Jasper Aug 09 '12 at 16:26