mashjprime
mashjprime

Reputation: 13

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. 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>

Upvotes: 1

Views: 607

Answers (2)

NIV
NIV

Reputation: 486

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.

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>

Upvotes: 0

obscure
obscure

Reputation: 12891

The problem is your two local variables start and end inside the pressButton() function.

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 = Date.now();

The second time the pressButton function gets called the else block of the if-condition gets executed. Unfortunately though you lost the value of the start variable since you've re-defined it initially using:

  let start;

If you make start and end global variables instead it will work flawlessly.

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>

Upvotes: 2

Related Questions