我基本上有一个完成的秒表,除了毫秒外,它还能工作。我只想显示2位数的毫秒,但我有一个问题。这是我用来格式化时间输出的函数:
function timeFormatter(timeInMilliseconds) {
var time = new Date(timeInMilliseconds);
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
var milliseconds = time.getMilliseconds().toString().slice(0, 2);
if (minutes.length < 2) { minutes = '0' + minutes; }
if (seconds.length < 2) { seconds = '0' + seconds; }
if (milliseconds.length < 2) { milliseconds = '0' + milliseconds; }
return minutes + ' : ' + seconds + ' . ' + milliseconds;
}问题
例如,当我给这个函数一个3093的输入时,输出是00 : 03 . 93
当我给函数一个3105的输入(应该比前面的输入更大)时,输出是00 : 03 . 10。换句话说,我的秒表可以追溯几毫秒。
我不知道如何解决这个问题,任何帮助都将不胜感激。
发布于 2015-11-03 06:11:58
var hundredths = (time.getMilliseconds()/10).toFixed(2);你不是真的在寻找毫秒(千分之一秒,可以是三位数,0-999),你要的是百分之一秒。所以你取毫秒除以10,然后再循环。这会给你百分之一秒的数值。如果需要前导零,可以添加它:
var hundredths= (time.getMilliseconds()/10).toFixed(0);
if(hundredths.length < 2) hundredths= "0" + hundredths;注意,Number.prototype.toFixed返回一个字符串,而不是数字。
发布于 2015-11-03 06:30:25
您可以使用一个简单的pad函数,例如:
/* Pad num with leading zeros to minimum length
** If number length is equal to or greater than minimum length,
** return it unmodified.
**
** @param {number} num - number to pad
** @param {number} length - minimum length of padded number
*/
function pad(num, length) {
if ((''+num).length >= length) return num;
var lead = '0' + new Array(length).join('0')
return (lead + num).slice(-length);
}
document.write(pad(23,5)); // 00023
document.write('<br>' + pad(223,2)); // 223
然后删除所有if语句并使用:
return pad(minutes,2) + ' : ' + pad(seconds,2) + ' . ' + pad(milliseconds,3);发布于 2015-11-03 06:18:11
只需尝试以下代码来启动、停止和重置计时器
var elem = document.getElementById("my-stopwatch");
var timer = new Stopwatch(elem, {delay: 10});
// start the timer
timer.start();
// stop the timer
timer.stop();
// reset the timer
timer.reset();https://stackoverflow.com/questions/33492421
复制相似问题