【问题标题】:Stop jquery function after x secondsx秒后停止jquery函数
【发布时间】:2013-12-05 05:51:12
【问题描述】:

我正在我的网站上运行此脚本以显示来自我的网络摄像头的图像。图片5秒后刷新,但是我想让这个功能在30秒后停止,这样就不会浪费太多带宽了。我该怎么做?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Reload iframe for every 5 seconds</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
setInterval(refreshiframe, 5000);
});
function refreshiframe() {
$('#testframe').attr('src', $('#testframe').attr('src'));
}
</script>
</head>
<body>
<div>
<iframe id="testframe" src="http://50.21.204.200/snapshot.jpg" width="640px" height="480px"></iframe>
</div>
</body>
</html>

谢谢

【问题讨论】:

    标签: jquery function refresh webcam


    【解决方案1】:

    setTimeoutsetInterval 类似,只是它只调用一次回调。

    使用setTimeout 将未来的回调排队 30 秒,这将使用clearInterval 停止第一个间隔:

    var intervalID = setInterval(refreshiframe, 5000);
    
    setTimeout(function () { clearInterval(intervalID); }, 30000);
    

    【讨论】:

      【解决方案2】:

      您可以只跟踪自开始以来经过的时间,如果超过了时间,则不开始下一次超时。

      $(function() {
         var start = new Date().getTime();
      
         function run() {
             refreshiframe();
             // if we haven't exceeded 30 seconds, schedule the next refresh
             if ((new Date()).getTime() - start < (30 * 1000)) {
                 setTimeout(run, 5000);
             }
         }
         // do the first one
         setTimeout(run, 5000);
      
         function refreshiframe() {
             $('#testframe').attr('src', $('#testframe').attr('src'));
         }
      });
      

      或者,您可以只保留一个计数器并仅刷新一定次数,然后在该次数后取消间隔:

      $(function() {
         var cntr = 0;
      
         var interval = setInterval(function() {
             refreshiframe();
             // if we've already done the max number of refreshes, 
             //    then cancel the interval
             if (++cntr > 6) {
                 clearInterval(interval);
             }
         }, 5000);
      
         function refreshiframe() {
             $('#testframe').attr('src', $('#testframe').attr('src'));
         }
      });
      

      【讨论】: