【问题标题】:Ending SetInterval Function when leaving page in jquery mobile在jquery mobile中离开页面时结束SetInterval函数
【发布时间】:2012-08-06 20:21:11
【问题描述】:

我正在整理一个 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>

【问题讨论】:

  • 如果您不想弄乱听众,一个快速而肮脏的解决方案可能是在发生某种情况时清除间隔内的间隔(在这种情况下,如果页面是不再可见。有关可见性问题,请参阅stackoverflow.com/questions/178325/…)。

标签: javascript jquery jquery-mobile webcam setinterval


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助,看起来间隔正在加载和触发,但我收到 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());有什么想法吗?
  • 是的,.find() 是一个必须在 jQuery 对象上运行的方法,因为它是一个 jQuery 函数。我只缓存了this 而不是$(this)。我用这个修复编辑了这个问题。
猜你喜欢
  • 2011-12-28
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 2013-09-17
  • 2018-04-11
  • 1970-01-01
相关资源
最近更新 更多