在 Javascript 中切换 setInterval

我希望能够再次使用相同的按钮禁用此功能(再次单击它),因此它就像一个切换按钮一样可以启动计时器并在我想要的时候结束它。


<span id="timer"></span>


<script>

var startTime = Date.now();


function myFunction() {

var interval = setInterval(function() {

    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);

}

</script>


<button onclick="myFunction()">Click me</button>

另外,在这段代码中,秒数不断加起来超过 60,我希望每当秒计数器达到 60 时它们就重置为 0,这可能吗?


还有一件事,有没有办法在我停止/关闭该功能时记录计数时间?


我是初学者,所以我希望你能让我变得简单。


杨魅力
浏览 172回答 5
5回答

长风秋雁

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

慕工程0101907

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

慕田峪7331174

一旦你设置了一个变量,你就可以用 var IntervalsetInterval删除它;clearIntervalfunction doStuff() {&nbsp; var elapsedtime = Date.now() - startTime;&nbsp; var secs = Math.floor(elapsedtime / 1000);&nbsp; var minutes = Math.floor(elapsedtime / (1000 * 60));&nbsp; var hours = Math.floor(elapsedtime / (1000 * 60 * 60));&nbsp; document.getElementById("timer").innerHTML = hours.toFixed(0) + 'h ' +&nbsp;&nbsp; minutes.toFixed(0) + 'm ' + secs.toFixed(0) + 's';}function toggleStuff() {&nbsp; if(!interval) {&nbsp; &nbsp; interval = setInterval(doStuff, 1000)&nbsp; } else {&nbsp; &nbsp; clearInterval(interval)&nbsp; &nbsp; interval = null&nbsp; }}

拉莫斯之舞

您需要使用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)}

一只萌萌小番薯

const el = document.querySelector("#timer");const btn = document.querySelector("#timerBtn");const padd = (n) => n > 9 ? n : `0${n}`; // Adds a zero paddinglet isRun = false; // Boolean to check if Timer is runninglet itv = undefined; // Clearable interval referencelet startTime = undefined; // Date objectlet timesStarted = 1; // Count runsfunction renderButton() {&nbsp; btn.textContent = `${isRun? "STOP" : "START"} ${timesStarted}`;}function renderTime() {&nbsp; const elapsed = Date.now() - startTime || 0,&nbsp; &nbsp; s = Math.floor(elapsed / 1000),&nbsp; &nbsp; m = Math.floor(elapsed / (1000 * 60)),&nbsp; &nbsp; h = Math.floor(elapsed / (1000 * 60 * 60));&nbsp; el.textContent = `${h}h ${padd(m)}m ${padd(s)}s`;};function start() {&nbsp; isRun = true;&nbsp; startTime = Date.now();&nbsp; itv = setInterval(() => renderTime(), 1000 / 60);&nbsp; renderButton();};function stop() {&nbsp; isRun = false;&nbsp; clearInterval(itv);&nbsp; timesStarted += 1;&nbsp; renderButton();};function toggle() {&nbsp; isRun ? stop() : start();&nbsp; isRun != isRun;};btn.addEventListener("click", toggle);renderButton();renderTime();<button id="timerBtn"></button><br><span id="timer"></span>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript