目前我的计时器从两分钟开始倒计时。我需要的是一个停止和重置计时器的按钮。这是我的代码。
js
$(function () {
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$timerDisplay.show();
var timeRemaining = time;
var intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
});
HTML
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
这是计时器的工作代码笔,但不是颜色变化http://codepen.io/Chevex/pen/RNomGG
答案 0 :(得分:0)
尝试......
<强> HTML:强>
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
<button id="stopTimer" disabled>Stop and Reset Timer</button>
<强> JS:强>
$(function () {
var $startTimer = $('#startTimer');
var $stopTimer = $('#stopTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
var intervalId;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$stopTimer.prop('disabled', false);
$timerDisplay.show();
var timeRemaining = time;
intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining / 60) + ':' + timeRemaining % 60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
$stopTimer.click(function() {
time = 120;
$startTimer.prop('disabled', false);
$stopTimer.prop('disabled', true);
$timerDisplay.hide();
clearInterval(intervalId);
$timerDisplay.text("");
});
});
基本上,我移动了区间变量并创建了一个停止计时器按钮;点击功能使用类似于之前执行的代码执行重置。
jsFiddle: http://jsfiddle.net/rfornal/w29ofkek/
答案 1 :(得分:0)
创建一个输入按钮,如下所示
<input type='button' value="Stop" onclick="StopTimer();"/>
将您的代码更改为以下
var intervalId =null;
$(function () {
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$timerDisplay.show();
var timeRemaining = time;
intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
});
function StopTimer()
{
clearInterval(intervalId);
}