javascript秒表限制最长时间

javascript stopwatch limit maximum time

本文关键字:长时间 javascript      更新时间:2024-02-23

我有一个javascript秒表,以MM:SS(分钟:秒)显示时间。如果时间达到59:59 MM:SS,则应自动停止(直到用户再次点击"清除并开始"),而不是增加到60:00、60:01等。如何设置最长时间来防止这种情况发生下面的代码允许用户停止、启动、清除和保存秒表,这在不限制javascript允许的最长时间的情况下是完美的。如有任何帮助或文档链接,我们将不胜感激。

javascript:

<script type='text/javascript'>
var clsStopwatch = function () {
var startAt = 0;
var lapTime = 0;
var now = function () {
return (new Date()).getTime();
};
this.start = function () {
startAt = startAt ? startAt : now();
};
this.stop = function () {
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0;
};
this.clear = function () {
lapTime = 0;
startAt = 0;
};
this.time = function () {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = 0;
var newTime = '';
m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
newTime = pad(m, 2) + ':' + pad(s, 2);
return newTime;
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}
function save() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);           
}
function clearWatch() {
x.stop();
x.clear();
clearInterval(clocktimer);
update();
}
</script>

html/php:

<form action="save.php" method="POST"/>
<h1>Time: <span id="time"></span> <br/></h1> 
<!--<input type="text" name-"time">-->
<input type="hidden" value="" id="counter" name="counter">
<input type="button" value="Start" onclick="start();">
<input type="button" value="Stop" onclick="stop();">
<input type="button" value="Clear" onclick="clearWatch();">
<input type="submit" value="Save" onclick="save();">

更改时间函数,以便如果时间大于最大值,则返回最大

this.time = function () {
    var duration = lapTime + (startAt ? now() - startAt : 0);
    if (duration > max) {
        duration = max;
    }
    return duration ;
};

将max替换为表示最长持续时间的数值。

对于59:59,最大值为(1000*60*59)+(59*1000)。这是因为返回的时间表示是毫秒值,所以59分钟加59秒