我正在创建一个倒数计时器。所以这是我到目前为止的代码。
function countdownTimeStart() {
var el = document.getElementById('demo');
var cancel = document.getElementById('cancel');
/* Start count the time in timer panel */
var time = document.getElementById("picker-dates").value;
time = time.split(':');
var x = setInterval(function () {
// set hours, minutes and seconds, decrease seconds
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
console.log(time);
// create a function to handle the cancel
function cancelCountdown(){
el.innerHTML = "00:00:00";
clearInterval(x);
}
// attach listener to cancel if cancel button is clicked
cancel.addEventListener( 'click', cancelCountdown);
// if seconds are negative, set them to 59 and reduce minutes
if (time[2] == -1) {
time[1]--;
time[2] = 59
}
// if minutes are negative, set them to 59 and reduce hours
if (time[1] == -1) {
time[0]--;
time[1] = 59
}
// Output the result in an element with id="demo"
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval(x);
el.innerHTML = "00:00:00";
} else if (seconds < 10) {
el.innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
el.innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
}, 1000);}
所以我想为此创建一个暂停按钮。我提到类似的问题,例如Javascript - Pausing setInterval()。
似乎很容易在jquery中创建暂停选项。但我不知道如何将其应用到我的脚本中。有人可以帮助我。
答案 0 :(得分:1)
在暂停点击时,您可以创建一个像savedTime
这样的对象来保存time
数组的当前值。然后,点击start
后,您可以查看savedTime
中是否有任何内容。如果是,请将hours
,minutes
和seconds
分配给该对象的值;否则,将其值设置为输入中的默认值。例如,像:
var el = document.getElementById('demo');
var cancel = document.getElementById('cancel');
var savedTime;
function countdownTimeStart() {
/* Start count the time in timer panel */
var timeValue = document.getElementById("picker-dates").value;
var time;
if (savedTime) {
time = savedTime;
savedTime = null;
} else time = timeValue.split(':');
var x = setInterval(function () {
// set hours, minutes and seconds, decrease seconds
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
// rest of countdownTimeStart is as normal
// ...
});
// Attach this function to your pause button:
function pauseTimer() {
savedTime = time;
clearInterval(x);
}
}