在 jquery 移动中离开页面时结束 SetInterval 函数

Ending SetInterval Function when leaving page in jquery mobile

本文关键字:结束 SetInterval 函数 jquery 移动 离开      更新时间:2023-09-26

我正在整理一个jquery移动网站,其中包括几个单独的网络摄像头页面(*.htm)。 在这些页面上,我正在加载一个设置间隔函数,该函数每隔几秒钟刷新一次来自相机的图像抓取并模拟视频。

但是,当我使用导航链接或后退按钮返回索引.htm离开网络摄像头页面(网络摄像头.htm)时,问题发生了,网络摄像头.htm页面保留在 DOM 中并每隔几秒钟拉取一次图像。

如何在用户离开时清除页面或至少结束间隔?

<script type="text/javascript">
    function camfresh() {
        setInterval(function(){ $("#rmcam").attr("src", "image.jpg?"+new Date().getTime());},2000);
    }
</script>
您可以使用

pageshowpagehide事件来启动和停止间隔:

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选择器更改为更具体(目前他们将选择每个伪页面)。