javascript - 在 jquery mobile 中离开页面时结束 SetInterval 函数

标签 javascript jquery jquery-mobile webcam setinterval

我正在构建一个 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>

最佳答案

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

关于javascript - 在 jquery mobile 中离开页面时结束 SetInterval 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11835343/

相关文章:

javascript - jQuery 正则表达式 (regex)

html - 我可以在多页文档中使用多个主要元素吗?

javascript - 带有面板导航的 jQuery Mobile 多页面结构

javascript - 在 WP7 上存储数据?

JavaScript 函数语句

javascript - SEO 和 AngularJS

javascript - 使用 JavaScript 和 REST 从 SharePoint 列表中删除项目

javascript - 当鼠标离开时维护由悬停事件分配的类

javascript - 清除canvas html5中的上下文

javascript - Phantom.js : Use locally, npm已安装,jquery