There is no “counting in the background”. You are simply computing time difference between now and the starting time. This is a correct way, this is how all timers works.
To implement pause feature, you need to know when was the pause / resume clicked - this way you can then calculate total time by summing the individual intervals.
For example, imagine you click start, wait 4 seconds, then pause, then wait 2 seconds and then resume and then after 3 seconds stop. It would look like this:
// imagine each "-" is 1 second:
start - - - - pause - - resume - - - stop
How long was it running? You can compute it as a sum of difference between all start (or resume) and pause (or stop) events.
So in this case it’s:
(pause - start) + (stop - resume) = 7 seconds
So what you need to do is instead of storing a single value when the time started, store an array of all these events.
So for the example above, after pressing start, you would store:
[
{start: 1643100032706, },
]
Then after pressing pause, you would update it with stop time:
[
{start: 1643100032706, stop: 1643100034706},
]
Then after pressing resume, you would add a new item:
[
{start: 1643100032706, stop: 1643100036706},
{start: 1643100038706, },
]
And then after stop you would update the last item again:
[
{start: 1643100032706, stop: 1643100036706},
{start: 1643100038706, stop: 1643100041706},
]
And to compute total time you simply iterate all items in the array and sum all diffs. Piece of cake
.
EDIT:
PS: code to sum all diffs:
[
{start: 1643100032706, stop: 1643100036706},
{start: 1643100038706, stop: 1643100041706},
].reduce((acc, x) => acc + (x.stop - x.start), 0) // returns 7000
// although, if the "x.stop" can be missing (for the last event), use `acc + ((x.stop || Date.now()) - x.start)`