如何从setInterval()函数中获取剩余时间

时间:2018-02-01 21:41:03

标签: javascript jquery

我有以下代码

function startTimer(time) {
  var countDown = 0;
  var time1 = time * 60;
  x = setInterval(function() {
    time2 = time1--;
    if (time2 > 0) {
      document.getElementById("displayTime").innerHTML = time2;
    } else if (time2 == 0) {
      clearInterval(x);
    }
  }, 1000);
}
startTimer(30)
<span id=displayTime></span>

如何从代码中获取剩余时间并将其用于暂停/恢复目的。 (我打算将这个值应用到函数中)。

我尝试创建2个按钮暂停和恢复但不起作用。

 $("#start").on("click",function(){
   if (time2 < setTime){
     startTimer(time2);
   }
   else{
     startTimer(setTime);
   }

   });
   $("#stop").on("click",function(){
     clearInterval(x);
    })
    });

2 个答案:

答案 0 :(得分:0)

我从函数中取出了time2,并且在函数外部使x可用。这可以用来启动/恢复计时器。

var time2;
var timer;
function startTimer(time) {
  var countDown = 0;
  var time1 = time * 60;
  x = setInterval(function() {
    time2 = time1--;
    if (time2 > 0) {
      document.getElementById("displayTime").innerHTML = time2;
    } else if (time2 == 0) {
      clearInterval(x);
    }
  }, 1000);
  return x;
}

function pauseTimer() {
  clearInterval(timer);
}
function resumeTimer() {
  time = time2/60 || 30;
  timer = startTimer(time);
}
<span id=displayTime></span>
<button onclick="pauseTimer()">Pause</button>
<button onclick="resumeTimer()">Start/Resume</button>

答案 1 :(得分:0)

这使用输入框来设置开始时间,如果您不希望用户更改值,则可能需要将输入设置为readonly

var timerInterval = null;

function startTimer(time) {
  // Update input every second
  return setInterval(function() {
    document.getElementById("displayTime").value = --time;
    if (time < 1) {
      pause();
    }
  }, 1000);
}

function start() {
  // Get the current time to begin from
  var timeToStartFrom = document.getElementById("displayTime").value;
  timerInterval = startTimer(timeToStartFrom);
}

function pause() {
  // Clear the interval to stop the timer
  clearInterval(timerInterval);
}
<input id=displayTime value=30 />
<button onclick="pause()">Pause</button>
<button onclick="start()">Start</button>

最后,请记住,这不是一个准确的计时器。如果用户点击Pause,则计时器将增加最后一秒钟和该秒段内通过时间之间的差值。 (例如:在剩余的28.1秒暂停,输入仍将显示29秒,重新启动将在29秒开始。这有效地为计时器增加了0.9秒。)

有许多基于准确计时的图书馆,我建议除了一个基本的例子之外,还要寻找那些。

相关问题