5 回答

TA貢獻1757條經驗 獲得超7個贊
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// AA: Global variables to hold the number of clicks and the var startTime values...etc;
const secsInMinute = 60;
const minutesInHour = 60;
var numOfClicks = 0;
var startTime;
var interval;
var timerObject = {
secs : 0, minutes : 0, hours : 0
}
var lastTimerObject = []
var counter = -1;
function displayTimer(){
// The constant variables
const secsInMinute = 60;
const minutesInHour = 60;
document.getElementById("timer").innerHTML = timerObject.hours.toFixed(0) + 'h ' +
// AA: Subtract the number of elapsed minutesInHour passed from the captured minutes
(timerObject.minutes - (timerObject.hours * minutesInHour)).toFixed(0)+ 'm ' +
// AA: Subtract the number of elapsed secsInMinutes passed from the captured seconds
(timerObject.secs- (timerObject.minutes * secsInMinute)).toFixed(0) + 's';
}
function timer () {
var elapsedtime = Date.now() - startTime;
timerObject.secs = Math.floor(elapsedtime / 1000) ;
timerObject.minutes = Math.floor(elapsedtime / (1000 * 60)) ;
timerObject.hours = Math.floor(elapsedtime / (1000 * 60 * 60));
displayTimer();
};
function myFunction() {
// AA: Increment the numOfClicks to determine whether or not to start the timer
// or to save the timer values and then clear it
numOfClicks ++;
// AA: Move the startTime inside myFunction, so it captures the time
// when the user clicks the button, rather than when the document loads
startTime = Date.now();
if (numOfClicks % 2 == 1)// Start the timer
{
// AA: Start the timer
interval = setInterval(timer, 1000);
document.getElementById("timerBttn").textContent = "Stop Timer";
}
else // Save the timer values and then clear it
{
counter++;
// AA: Clear the timer
clearInterval(interval);
// Change the text on the button to Start Timer
document.getElementById("timerBttn").textContent = "Start Timer";
// Save the timer values to currentTimer Object and reset the
// timerObject to zeros.
lastTimerObject[counter] = {};
lastTimerObject[counter].secs = timerObject.secs;
lastTimerObject[counter].minutes = timerObject.minutes;
lastTimerObject[counter].hours =timerObject.hours;
timerObject.secs = 0;
timerObject.minutes = 0;
timerObject.hours = 0;
displayTimer();
// AA: The alert is optional, just to display the last timer val before stoppage
alert ('Current Timer Value: ' + lastTimerObject[counter].hours.toFixed(0) + 'h ' +
(lastTimerObject[counter].minutes - (lastTimerObject[counter].hours * minutesInHour)).toFixed(0)+ 'm ' +
(lastTimerObject[counter].secs- (lastTimerObject[counter].minutes * secsInMinute)).toFixed(0) + 's');
lastTimerObject[counter].secs = (lastTimerObject[counter].secs- (lastTimerObject[counter].minutes * secsInMinute)).toFixed(0);
lastTimerObject[counter].minutes = (lastTimerObject[counter].minutes - (lastTimerObject[counter].hours * minutesInHour)).toFixed(0) ;
// console.log("lastTimerObject.hours " + lastTimerObject[counter].hours + " lastTimerObject.minutes " + lastTimerObject[counter].minutes + " lastTimerObject.secs " + lastTimerObject[counter].secs );
console.log ("Timer Values:")
for (var item of lastTimerObject)
{
console.log(item.hours + "h " + item.minutes + "m " + item.secs + "s");
}
}
}
</script>
<!--AA: Chnaged the name of the button to indicate start/stop timer to user clearly
and added id to the button to maniplulate the name within the JavaScript-->
<button id="timerBttn" onclick="myFunction()">Start Timer</button>
<span id="timer"></span>
</body>
</html>

TA貢獻1887條經驗 獲得超5個贊
我的方式...
(function() // IIFE
{
const theTimmer = document.getElementById('timer')
, theButton = document.getElementById('the-button')
, twoDigits = n => n>9?n:`0${n}`
, one_sec = 1000
, one_min = one_sec *60
, one_hour = one_min *60
;
let interval = null
, startTime = null
, count = 1
, onRun = false
;
theButton.textContent = `Start : 1`
theButton.onclick=_=>
{
if (onRun)
{
clearInterval(interval)
onRun = false
theButton.textContent = `Start : ${++count}`
}
else
{
theButton.textContent = `Stop : ${count}`
onRun = true
startTime = Date.now()
interval = setInterval(()=>
{
let tim = Date.now() -startTime
, h = ~~(tim /one_hour)
, m = ~~((tim %one_hour) /one_min)
, s = ~~((tim %one_min) /one_sec)
;
theTimmer.textContent = `${h}h ${twoDigits(m)}m ${twoDigits(s)}s`
}
, 250);
}
}
})()
<p id="timer"> -- </p>
<button id="the-button">Click me</button>

TA貢獻1828條經驗 獲得超13個贊
一旦你設置了一個變量,你就可以用 var IntervalsetInterval刪除它;clearInterval
function doStuff() {
var elapsedtime = Date.now() - startTime;
var secs = Math.floor(elapsedtime / 1000);
var minutes = Math.floor(elapsedtime / (1000 * 60));
var hours = Math.floor(elapsedtime / (1000 * 60 * 60));
document.getElementById("timer").innerHTML = hours.toFixed(0) + 'h ' +
minutes.toFixed(0) + 'm ' + secs.toFixed(0) + 's';
}
function toggleStuff() {
if(!interval) {
interval = setInterval(doStuff, 1000)
} else {
clearInterval(interval)
interval = null
}
}

TA貢獻1820條經驗 獲得超10個贊
您需要使用clearInterval來清除間隔。
<script>
var startTime = Date.now();
let timerStarted = false; //created a temp variable to know whether interval started.
let interval; // set the interval as a global variable so it can be reset.
function myFunction() {
if (!timerStarted) { //if it's not started, start it
? ? interval = setInterval(function() { //use the global variable to store the interval
? ? timerStarted = true; //set it to true so we know it started
? ? var elapsedtime = Date.now() - startTime;
? ? var secs = Math.floor(elapsedtime / 1000);
? ? var minutes = Math.floor(elapsedtime / (1000 * 60));
? ? var hours = Math.floor(elapsedtime / (1000 * 60 * 60));
? ? document.getElementById("timer").innerHTML = hours.toFixed(0) + 'h ' + minutes.toFixed(0) + 'm ' + secs.toFixed(0) + 's';
}, 1000);
} else {
? clearInterval(interval) //if it's started, clear the timer.
}
}
</script>
另外,在這段代碼中,秒數不斷加起來超過 60,我希望每當秒計數器達到 60 時它們就重置為 0,這可能嗎?
這不是代碼中的 JavaScript 問題,而是數學問題。
var secs = Math.floor(elapsedtime / 1000);
您希望它重置為 0,然后您需要檢查秒數。例如,如果過去了 70 秒,我想刪除 60 秒,剩下 10 秒(10 秒是你想要的值)。
為此,請參閱https://stackoverflow.com/a/41633001/2822041
還有一件事,有沒有辦法在我停止/關閉該功能時記錄計數時間?
這不是一個問題。您也需要為此使用一個變量。
例如
let timerCount = 0;
function myFunction() {
? ?interval = setInterval(() => {
? ? ? ?timerCount++;
? ? ? ?console.log('Elapsed ', timerCount)
? ?}, 1000)
}

TA貢獻1795條經驗 獲得超7個贊
const el = document.querySelector("#timer");
const btn = document.querySelector("#timerBtn");
const padd = (n) => n > 9 ? n : `0${n}`; // Adds a zero padding
let isRun = false; // Boolean to check if Timer is running
let itv = undefined; // Clearable interval reference
let startTime = undefined; // Date object
let timesStarted = 1; // Count runs
function renderButton() {
btn.textContent = `${isRun? "STOP" : "START"} ${timesStarted}`;
}
function renderTime() {
const elapsed = Date.now() - startTime || 0,
s = Math.floor(elapsed / 1000),
m = Math.floor(elapsed / (1000 * 60)),
h = Math.floor(elapsed / (1000 * 60 * 60));
el.textContent = `${h}h ${padd(m)}m ${padd(s)}s`;
};
function start() {
isRun = true;
startTime = Date.now();
itv = setInterval(() => renderTime(), 1000 / 60);
renderButton();
};
function stop() {
isRun = false;
clearInterval(itv);
timesStarted += 1;
renderButton();
};
function toggle() {
isRun ? stop() : start();
isRun != isRun;
};
btn.addEventListener("click", toggle);
renderButton();
renderTime();
<button id="timerBtn"></button><br>
<span id="timer"></span>
添加回答
舉報