【发布时间】:2021-05-09 09:04:08
【问题描述】:
更新
设法从现在 01:02:03 开始。startTime = new Date().getTime()-(seconds);
但是当我恢复秒表时,它不会从暂停的地方继续。 例如, 我在 00:07:45 暂停了。我想恢复它,但我得到了 00:15:30。
你好吗?希望你们今天或晚上过得愉快。
所以我这里有个小问题。我有一个秒表。我希望秒表从显示的特定时间开始运行。
例如, 现在秒表上显示的时间是 01:02:03。我希望秒表从 01:02:03 开始。
我对此进行了研究。它与 Epoch Javascript 有关。我将 01:02:03 转换为毫秒。但它不是从 01:02:03 开始的。相反,它从 22:52:34 开始。
我不知道我哪里做错了。请赐教。
脚本
/*Global variables here*/
var startTime;
var updatedTime;
var difference;
var tInterval;
var savedTime;
var paused = 0;
var running = 0;
/**This function is triggered when user starts the stopwatch.**/
function startTimer(){
if(!running){
// getting the displayed time
startTime = document.querySelector('#stopwatch_display').innerText;
var a = startTime.split(':');
var seconds = (a[0]*1000*60*60)+(a[1]*1000*60)+(a[2]*1000);
startTime = new Date(seconds+1);
tInterval = setInterval(getShowTime, 1);
// change 1 to 1000 above to run script every second instead of every millisecond. one other change will be needed in the getShowTime() function below for this to work. see comment there.
paused = 0;
running = 1;
// Some styling here
}
}
/**This function is triggered when user pauses and resumes the stopwatch.**/
function pauseTimer(){
if (!difference){
// if timer never started, don't allow pause button to do anything
} else if (!paused) {
clearInterval(tInterval);
savedTime = difference;
paused = 1;
running = 0;
// Some styling here
} else {
// if the timer was already paused, when they click pause again, start the timer again
startTimer();
}
}
/**This function is triggered when user resets the stopwatch.**/
function resetTimer(){
clearInterval(tInterval);
savedTime = 0;
difference = 0;
paused = 0;
running = 0;
// Some styling here
}
/**This function is to display the time.**/
function getShowTime(){
updatedTime = new Date().getTime();
if (savedTime){
difference = (updatedTime - startTime) + savedTime;
} else {
difference = updatedTime - startTime;
}
var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((difference % (1000 * 60)) / 1000);
//var milliseconds = Math.floor((difference % (1000 * 60)) / 100);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
//milliseconds = (milliseconds < 100) ? (milliseconds < 10) ? "00" + milliseconds : "0" + milliseconds : milliseconds;
timerDisplay.innerHTML = hours + ':' + minutes + ':' + seconds;
}
【问题讨论】:
-
有没有理由在 startTimer 函数中重新分配 startTime 两次?此外,该变量并未出现在该函数中。它在 getShowTimes 中使用,为什么不将它作为参数传递呢?另外,什么是 updatedTime,它是如何计算的?
-
@Hyetigran
startTime实际上是一个全局变量。用了两次,因为我想更新startTime。 updatedTime 也是一个全局变量。嗯..如果您阅读getShowTimes的代码 sn-p,它会通过 getTime 函数获取毫秒数。 -
@Hyetigran 添加了所有全局变量。
标签: javascript epoch stopwatch