如何暂停setInterval()函数? [英] How can I pause setInterval() functions?

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

问题描述

如何使用Java脚本暂停和恢复setInterval()函数?

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

例如,也许我有一个秒表来告诉您您浏览网页的秒数.有一个暂停"和恢复"按钮. clearInterval()在此处不起作用的原因是,如果用户在第40秒和第800毫秒单击暂停"按钮,则当他单击恢复"按钮时,经过200秒后,必须经过的秒数必须增加1.如果我在计时器变量上使用clearInterval()函数(单击暂停按钮时),然后在计时器变量上再次使用setInterval()函数(单击恢复按钮时),经过的秒数将增加仅在1000毫秒后返回1,这会破坏秒表的准确性.

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.

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

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