为了账号安全,请及时绑定邮箱和手机立即绑定

在 Javascript 中切换 setInterval

在 Javascript 中切换 setInterval

杨魅力 2023-08-18 16:17:20
我希望能够再次使用相同的按钮禁用此功能(再次单击它),因此它就像一个切换按钮一样可以启动计时器并在我想要的时候结束它。<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,这可能吗?还有一件事,有没有办法在我停止/关闭该功能时记录计数时间?我是初学者,所以我希望你能让我变得简单。
查看完整描述

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>


查看完整回答
反对 回复 2023-08-18
?
慕工程0101907

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>


查看完整回答
反对 回复 2023-08-18
?
慕田峪7331174

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

  }

}


查看完整回答
反对 回复 2023-08-18
?
拉莫斯之舞

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)

}


查看完整回答
反对 回复 2023-08-18
?
一只萌萌小番薯

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>


查看完整回答
反对 回复 2023-08-18
  • 5 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信