JavaScript 编码练习:利用一个按钮实现开始计时和停止计时

问题描述

        页面上有一个按钮,点击按钮开始计时,页面上显示经过了多少时间,再次点击计时停止。

页面显示如下:

        

<html>
 <head>
 </head>
 <body>
  <button id="start">Start</button>
   <p><span id="counter">0</span> elapsed second(s)</p> 
 </body>
</html>

解决办法

        我的:

//Write-Your-Code-Here
const counterElement = document.getElementById("counter");
const buttonElement = document.getElementById("start");
let intervalId;
const addSeconds = () =>
{
    const counter = Number(counterElement.textContent);
    counterElement.textContent = counter + 1;
};
buttonElement.addEventListener("click",e =>{
    if(buttonElement.textContent === "Start")
    {
        intervalId = setInterval(addSeconds, 1000);
        buttonElement.textContent = "Stop";
    }
    else
    {
        clearInterval(intervalId);
        buttonElement.textContent = "Start";
    }

});

        参考答案:

const buttonElement = document.querySelector("button");
const counterElement = document.getElementById("counter");
// Global variable to access it from function
let intervalId = null;
// Chronometer state, initially stopped
let started = false;

buttonElement.addEventListener("click", () => {
  if (!started) {
    // Start the chronometer: add 1 to the counter each second
    intervalId = setInterval(() => {
      counterElement.textContent = String(Number(counterElement.textContent) + 1);
    }, 1000);
    // Update button text
    buttonElement.textContent = "Stop";
  } else {
    // Stop the chronometer
    clearInterval(intervalId);
    // Update button text
    buttonElement.textContent = "Start";
  }
  // Change chronometer state
  started = !started;
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值