我正在尝试创建一个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)
是当前日期。如果计时器的新值在窗口/标签关闭时仍然运行,那么最好的计算方法是什么?
答案 0 :(得分:1)
这可能与某些改进有关,但是在找到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的计时器时间。然后计算出已经过了多少时间并添加了一个。
答案 1 :(得分: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)
);