如何在 JavaScript 中计算秒表/计时器
How to calculate stopwatch/timer in JavaScript
我正在尝试创建一个jQuery/JavaScript计时器,即使您离开页面,它也会继续运行。
我尝试了一些插件来做到这一点,但最终我发现作为起点效果最好的是用户Daniel_Hug遇到的一个 jsfiddle:
http://jsfiddle.net/Daniel_Hug/pvk6p/
我已经更新了它以包括 Bootstrap 3,添加了一些用于响应的样式,并将计时器的时间保存到 cookie 中,以便在您离开页面时它继续从中断的地方继续。这是我的更新版本:
http://jsfiddle.net/ezrafree/hgks67u0/
.HTML:
<div class="container">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"></time>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success">START</button>
<button id="stop" class="btn btn-danger" disabled="disabled">STOP</button>
<button id="reset" class="btn btn-default" disabled="disabled">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"></div>
</div>
</div>
JavaScript:
/**
* jQuery Stopwatch
* by @websightdesigns
*
* Based on "Javascript Stopwatch" by Daniel Hug
* From http://jsfiddle.net/Daniel_Hug/pvk6p/
* Modified to:
* - add responsive css styles
* - add save functionality with cookies
*/
// Initialize our variables
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
t;
// Get time from cookie
var cookieTime = getCookie('time');
// If timer value is saved in the cookie
if( cookieTime != null && cookieTime != '00:00:00' ) {
var savedCookie = cookieTime;
var initialSegments = savedCookie.split('|');
var savedTimer = initialSegments[0];
var timerSegments = savedTimer.split(':');
var seconds = parseInt(timerSegments[2]),
minutes = parseInt(timerSegments[1]),
hours = parseInt(timerSegments[0]);
timer();
document.getElementById('timerValue').textContent = savedTimer;
$('#stop').removeAttr('disabled');
$('#reset').removeAttr('disabled');
} else {
var seconds = 0, minutes = 0, hours = 0;
timerDiv.textContent = "00:00:00";
}
// New Date object for the expire time
var curdate = new Date();
var exp = new Date();
// Set the expire time
exp.setTime(exp + 2592000000);
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
timerDiv.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00")
+ ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00")
+ ":" + (seconds > 9 ? seconds : "0" + seconds);
// Set a 'time' cookie with the current timer time and expire time object.
var timerTime = timerDiv.textContent.replace("%3A", ":");
// console.log('timerTime', timerTime);
setCookie('time', timerTime + '|' + curdate, exp);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
// timer(); // autostart timer
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
reset.onclick = function() {
timerDiv.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
setCookie('time', "00:00:00", exp);
}
/**
* Javascript Stopwatch: Button Functionality
* by @websightdesigns
*/
$('#start').on('click', function() {
$('#stop').removeAttr('disabled');
$('#reset').removeAttr('disabled');
});
$('#stop').on('click', function() {
$(this).prop('disabled', 'disabled');
});
$('#reset').on('click', function() {
$(this).prop('disabled', 'disabled');
});
/**
* Javascript Stopwatch: Cookie Functionality
* by @websightdesigns
*/
function setCookie(name, value, expires) {
document.cookie = name + "=" + value + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie(name) {
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
/**
* TODO: Continue timing the timer while the browser window is closed...
*/
.CSS:
/**
* jQuery Stopwatch
* by @websightdesigns
*/
#timeContainer,
#timerButtons {
margin-left: auto;
margin-right: auto;
}
#timeContainer {
margin-top: 1em;
}
#timerValue {
font-size: 1.5em;
}
#timerButtons {
text-align: center;
}
#timerButtons button {
font-size: 0.8em;
}
@media (min-width: 768px) {
#timeContainer,
#timerButtons {
width: 210px;
}
}
@media (max-width: 767px) {
#timeContainer {
width: 184px;
}
#timerButtons button {
max-width: 32.75%;
display: inline-block;
}
}
@media (max-width: 240px) {
#timeContainer {
width: 100%;
}
#timerButtons button {
width: 100%;
max-width: 100%;
clear: both;
display: block;
margin-bottom: 0.75em;
}
}
/**
* jQuery Stopwatch
* by @websightdesigns
*/
#timeContainer,
#timerButtons {
margin-left: auto;
margin-right: auto;
}
#timeContainer {
margin-top: 1em;
}
#timerValue {
font-size: 1.5em;
}
#timerButtons {
text-align: center;
}
#timerButtons button {
font-size: 0.8em;
}
@media (min-width: 768px) {
#timeContainer,
#timerButtons {
width: 210px;
}
}
@media (max-width: 767px) {
#timeContainer {
width: 184px;
}
#timerButtons button {
max-width: 32.75%;
display: inline-block;
}
}
@media (max-width: 240px) {
#timeContainer {
width: 100%;
}
#timerButtons button {
width: 100%;
max-width: 100%;
clear: both;
display: block;
margin-bottom: 0.75em;
}
}
如您所见,我正在使用如下值保存我的 cookie:
00:02:28|Mon Mar 16 2015 10:29:42 GMT-0600 (MDT)
在上面的示例中,00:02:28
是计时器的当前时间,Mon Mar 16 2015 10:29:42 GMT-0600 (MDT)
是当前日期。如果计时器在窗口/选项卡关闭时仍在运行,计算计时器的新值的最佳方法是什么?
这可能与一些改进有关,但在找到 cookie 时运行的代码中:
var date = new Date(initialSegments[1]);
date.setHours(date.getHours() + parseInt(timerSegments[0],10), date.getMinutes() + parseInt(timerSegments[1],10), date.getSeconds() + parseInt(timerSegments[2],10));
var secsDiff = ((date - new Date(initialSegments[1]))/1000);
var seconds = secsDiff%60,
minutes = Math.floor(secsDiff/60),
hours = Math.floor(secsDiff/(60*60));
add();
这样做是从cookie中获取时间,并添加上次计时器时间,该时间也已保存到cookie中。然后,它会计算出经过了多少时间并添加该时间。
在这里尝试一下:http://jsfiddle.net/hgks67u0/1/
如果有人仍在寻找完整的解决方案,我采用了@Jamiec的解决方案,并在一个多计时器上构建了一个多计时器,当您关闭窗口、切换选项卡或导航离开页面时,该计时器即可工作。可能会为某人指明正确的方向。
关键的区别在于我必须将这点逻辑添加到@Jamiec的解决方案中。
var savedCookie = cookieTime,
initialSegments = savedCookie.split('|'),
savedTimer = initialSegments[0],
timerSegments = savedTimer.split(':'),
date = new Date(initialSegments[1]);
var currentTimeDifference = Math.round((new Date() - date)/1000);
if (localStorage[elements[index].timerName + '_started'] == 'true') {
date.setHours(
date.getHours() + parseInt(currentTimeDifference / (60 * 60), 10),
date.getMinutes() + parseInt(Math.floor(currentTimeDifference / 60), 10),
date.getSeconds() + parseInt(currentTimeDifference % 60, 10)
);
}
date.setHours(
date.getHours() + parseInt(timerSegments[0], 10),
date.getMinutes() + parseInt(timerSegments[1], 10),
date.getSeconds() + parseInt(timerSegments[2], 10)
);
https://jsfiddle.net/asherkhan111/ogvyd1xv/2/
- 如何在窗体打开时从javascript倒计时计时器值中节省时间
- 设置倒计时计时器,IE出现问题
- MobileFirst:在客户端运行计时器作业-最佳选项
- 显示具有服务器端自动时间注销的同步倒计时计时器
- 倒计时计时器应该持续两个php页面
- 在Jquery倒计时计时器上设置每个数字的动画
- 我如何才能确保计时器设置为每天4点半,所以我不会;不用在Javascript中提及某个日期
- 如何禁用窗口.当计时器超时时,打开卸载警报
- 在Nodejs中为许多用户处理计时器
- 如果弹出窗口关闭,Javascript停止/重置计时器
- 如何在隐藏时暂停jquery计时器
- Javascript倒计时计时器倒计时未正确更新秒/分钟
- 计时器循环从不运行
- Progressbar计时器,仅在页面刷新时重新加载
- 创建一个倒计时计时器脚本,该脚本计算声音文件的持续时间,而不是特定的日期
- 递归倒计时计时器
- 如何在 JavaScript 中计算秒表/计时器
- 用javascript计算计时器,刷新时保持时间
- 如何在javascript中创建计时器,并在指定时间内计算点击次数
- JQuery时钟/计时器,因为页面被加载(即使用户改变他的计算机上的时间)