如何在 JavaScript 中计算秒表/计时器

How to calculate stopwatch/timer in JavaScript

本文关键字:计时器 计算 JavaScript      更新时间:2023-09-26

我正在尝试创建一个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/