javascript秒表限制最长时间

时间:2015-02-20 00:04:53

标签: javascript

我有一个javascript秒表,用MM显示时间:SS(分钟:秒)。如果时间达到59:59 MM:SS那么它应该自动停止(直到用户再次点击Clear and Start)而不是增加到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();">

1 个答案:

答案 0 :(得分:1)

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

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秒