javascript - JS倒计时器-暂停功能

标签 javascript timer

这是一个简单的倒计时器,从 9 倒数到 0。 倒计时效果很好。但是,如果我想在流程中暂停它,然后从暂停的地方重新启动怎么办? 我尝试过(参见下面的代码)中断倒计时,保存其所在的数字,然后从新数字重新启动该功能。但倒计时变得困惑,我不明白为什么。有什么想法吗?

PS。我可以从其他地方剪切并粘贴计时器,但我这样做是为了学习体验。我确信有更好的方法在 JS 中编写倒计时器,但我无法让这种方式工作并认为我一定错过了一些明显的东西,这让我很烦恼。

非常感谢

var currentTimeInt = 10;
var minn = [];
var stop = 0;

 // stop
 function stopCounter() {
 currentTime = document.getElementById('mins').textContent; // grabs the number of minutes at moment of pause.

 stop = 1;
  }
 
 // restart
 function restart() {
 stop = 0;
 currentTimeInt = parseInt(currentTime, 10); // converts that number into an integer we can use
 document.getElementById("mins").innerHTML=currentTimeInt;
  newMinutes(); // restarts the newMinutes function with the start time currentTimeInt set to the time the counter stopped at
   }
 
function newMinutes() {
document.getElementById('mins').innerHTML= currentTimeInt; // displays the counter

for (aa = currentTimeInt-1; aa >= 0; aa--) {
minn.push(aa); // builds an array of numbers in descending order
document.getElementById('mins').innerHTML= minn[aa]; 
for (let bb=1; bb<=currentTimeInt; bb++) {
if (bb<currentTimeInt) {
    setTimeout( function timer(){
	if (stop == 0) {     // checks if "stop!" has been clicked and returns false to stop the function if that is the case
        document.getElementById('mins').innerHTML= minn[bb];
		console.log(minn[bb]);
	}
	else {return false;}
		}, bb*1000 );
	}

}	
}
console.log(currentTimeInt + " the end");

}
<span>Minutes: </span><span id= "mins"></span>
<button onclick="newMinutes()">Go!</button>
<button onclick="stopCounter()">Stop!</button>
<button onclick="restart()">Reset!</button>

最佳答案

您可以尝试以下示例:

var timerId;
var counter;

function start() {
  console.log('start');
  if (!counter) {
    reset();
  } else {
    loop();
  }
}

function pause() {
  console.log('pause');
  if (timerId) {
    clearInterval(timerId);
    timerId = null;
  }
}

function reset() {
  console.log('reset');
  pause();
  counter = 10;
  loop();
}

function loop() {
  timerId = setInterval(function() {
    if (0 >= counter) {
      pause();
      return;
    }
    console.log('counter', counter);
    counter--;
  }, 500);
}
<button onclick='start();'>Start</button>
<button onclick='pause();'>Pause</button>
<button onclick='reset();'>Reset</button>

关于javascript - JS倒计时器-暂停功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45522240/

相关文章:

javascript - S3 替代方案,允许在不缓冲的情况下上传流文件

javascript - 在 ng-repeat 中显示子数组

Android:如何在超时时清除 EditText?

Javascript - 测量 FPS 并将其与事件同步

javascript - Angular 未检测到来自 postMessage 的新窗口中 ngFor 的变化

javascript - 检查对象何时触及 Canvas 边框并执行其他动画

javascript - GraphQL 和 Hibernate (ORM)

c - 我如何在C中获得持续时间

python - Threading.Timer(5, function) 每 5 秒启动一次

c - Linux 中的周期性任务