[英]Calculating elapsed time between button press in Javascript
I'm trying to calculate the time between when button is pushed for the first and second time.我正在尝试计算第一次和第二次按下按钮之间的时间。 Performing arithmetic on a single variable works fine (ie. end-1) but if I try to do (end - start), the result is NaN.对单个变量执行算术工作正常(即 end-1),但如果我尝试执行(结束 - 开始),结果为 NaN。 Have I missed something simple here?我在这里错过了一些简单的东西吗? Thank you.谢谢你。
function pressButton() { let start; let end; if (timerControl.innerHTML == "Start") { timerControl.innerHTML = "Stop"; start = Date.now(); console.log(start); } else { timerControl.innerHTML = "Start"; end = Date.now(); console.log(end); } let timeElapsed = (end - start); console.log(timeElapsed); }
<button onclick="pressButton()" id="timerControl">Start</button>
The problem is your two local variables start and end inside the pressButton() function.问题是你的两个局部变量在 pressButton() 函数内开始和结束。
When you first click on your button this condition will evaluate to true:当您第一次单击按钮时,此条件将评估为真:
if (timerControl.innerHTML == "Start")
This means the variable start will have a value这意味着变量 start 将有一个值
start = Date.now();
The second time the pressButton function gets called the else block of the if-condition gets executed.第二次调用 pressButton 函数时,将执行 if 条件的 else 块。 Unfortunately though you lost the value of the start variable since you've re-defined it initially using:不幸的是,尽管您丢失了 start 变量的值,因为您最初使用以下方法重新定义了它:
let start;
If you make start and end global variables instead it will work flawlessly.如果您使用start和end全局变量,它将完美地工作。
let end; let start; function pressButton() { if (timerControl.innerHTML == "Start") { timerControl.innerHTML = "Stop"; start = Date.now(); console.log(start); } else { timerControl.innerHTML = "Start"; end = Date.now(); console.log(end); let timeElapsed = (end - start); console.log(timeElapsed); } }
<button onclick="pressButton()" id="timerControl">Start</button>
You are declaring start and end every time the button is clicked irrespective of "STOP" or "START".每次单击按钮时,您都在声明开始和结束,而不管“停止”或“开始”。 Also you are calculating the timeElapsed before end is even assigned a value.此外,您正在计算 end 之前的 timeElapsed 甚至被分配一个值。
let start=0; let end=0; let timeElapsed; function pressButton() { if (timerControl.innerHTML == "Start") { timerControl.innerHTML = "Stop"; start = Date.now(); timeElapsed = 0; console.log("Start:"+start); } else { timerControl.innerHTML = "Start"; end = Date.now(); console.log("end:"+end); timeElapsed = (end - start); } console.log("timeElapsed:"+timeElapsed); }
<button onclick="pressButton()" id="timerControl">Start</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.