我正在整理一个jquery移动网站,其中包括几个单独的网络摄像头页面(*.htm)。 在这些页面上,我正在加载一个设置间隔函数,该函数每隔几秒钟刷新一次来自相机的图像抓取并模拟视频。
但是,当我使用导航链接或后退按钮返回索引.htm离开网络摄像头页面(网络摄像头.htm)时,问题发生了,网络摄像头.htm页面保留在 DOM 中并每隔几秒钟拉取一次图像。
如何在用户离开时清除页面或至少结束间隔?
<script type="text/javascript">
function camfresh() {
setInterval(function(){ $("#rmcam").attr("src", "image.jpg?"+new Date().getTime());},2000);
}
</script>
您可以使用
pageshow
和pagehide
事件来启动和停止间隔:
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);
});
您可以将.ui-page
选择器更改为更具体(目前他们将选择每个伪页面)。