Measure on time

I notice that, in your code, totalTime does not advance while the switch is closed. It only advances once the switch becomes open.

To have the totalTime variable advance in real time, you could have the heartbeat code do the timing. Something like:

  if (millis() - heartbeatMillis >= 20)
  {
    //restart the TIMER
    heartbeatMillis += 20;

    //toggle LED
    digitalWrite(heartbeatLED, ((heartbeatMillis / 500) & 1));

    if (digitalRead(mySwitch)==CLOSED) {
      totalTime += 20;
      if ((totalTime % 100) < 20)
      {
        Serial.print((totalTime / 1000.0), 1);
        Serial.println(" s");
      }
    }
  }