Javascript - 暂停setInterval() [英] Javascript - Pausing setInterval()

查看:146
本文介绍了Javascript - 暂停setInterval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Javascript暂停和恢复setInterval()函数?

How do I pause and resume the setInterval() function using Javascript?

例如,我可能有一个秒表来告诉你你拥有的秒数一直在看网页。有一个暂停和恢复按钮。 clearInterval()在这里不起作用的原因是因为如果用户在第40秒和第800毫秒点击暂停按钮,当他点击恢复按钮时,经过的秒数必须在200毫秒后增加1。如果我在timer变量上使用clearInterval()函数(单击暂停按钮时),然后再次对timer变量使用setInterval()函数(单击恢复按钮时),经过的秒数将增加1仅在1000毫秒后,这会破坏秒表的准确性。

For example, maybe I have a stopwatch to tell you the number of seconds that you have been looking at the webpage. There is a 'Pause' and 'Resume' button. The reason why clearInterval() would not work here is because if the user clicks on the 'Pause' button at the 40th second and 800th millisecond, when he clicks on the 'Resume' button, the number of seconds elapsed must increase by 1 after 200 milliseconds. If I use the clearInterval() function on the timer variable (when the pause button is clicked) and then using the setInterval() function on the timer variable again (when the resume button is clicked), the number of seconds elapsed will increase by 1 only after 1000 milliseconds, which destroys the accuracy of the stopwatch.

那我该怎么做?

推荐答案

您可以使用标记来跟踪状态:

You could use a flag to keep track of the status:

var output = $('h1');
var isPaused = false;
var time = 0;
var t = window.setInterval(function() {
  if(!isPaused) {
    time++;
    output.text("Seconds: " + time);
  }
}, 1000);

//with jquery
$('.pause').on('click', function(e) {
  e.preventDefault();
  isPaused = true;
});

$('.play').on('click', function(e) {
  e.preventDefault();
  isPaused = false;
});

h1 {
    font-family: Helvetica, Verdana, sans-serif;
    font-size: 12px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Seconds: 0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>

这就是我要做的,我不确定你是否可以实际暂停setInterval。

This is just what I would do, I'm not sure if you can actually pause the setInterval.

注意:这个系统非常简单,适用于不需要高精度的应用程序,但它不会考虑在刻度之间经过的时间:如果你在半秒后点击暂停,然后点击播放你的时间将是休息了半秒钟。

Note: This system is easy and works pretty well for applications that don't require a high level of precision, but it won't consider the time elapsed in between ticks: if you click pause after half a second and later click play your time will be off by half a second.

这篇关于Javascript - 暂停setInterval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆