我正在构建一个 jquery 移动网站,其中包含几个用于网络摄像头的单独页面 (*.htm)。在这些页面上,我正在加载一个设置的间隔函数,该函数每隔几秒刷新一次从相机抓取的图像并模拟视频。
但是,当我使用导航链接或后退按钮导航离开网络摄像头页面 (webcam.htm) 返回到 index.htm 时,就会出现问题,webcam.htm 页面仍保留在 DOM 中,并且每隔几秒就会拉取图像.
当用户离开时,如何清除页面或至少清除 endinterval?
<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
选择器更改为更具体(目前它们将选择每个伪页面)。
关于javascript - 在 jquery mobile 中离开页面时结束 SetInterval 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11835343/