JavaScript Lesson Start and Stop Timer GetTime For Timer using Date

GetTime For Timer using Date
How to set up a timer based on a JavaScript Date object. This project will create a set of buttons that can start and stop a timer. The timer values are based on the ECMAScript epoch from the Date object in JavaScript that can be returned using getTime(). This format will provide a more exact time calculation as the time will be returned and calculated.

Select the page elements and create a start and stop button. If you create the elements in JavaScript like the code below you can also set the styling with the element style object properties.

const main = document.querySelector(‘.main’);
const timer = document.createElement(‘div’);
const btn1 = document.createElement(‘button’);
const btn2 = document.createElement(‘button’);
main.append(timer);
main.append(btn1);
main.append(btn2);

btn1.style.backgroundColor = ‘green’;
btn2.style.backgroundColor = ‘red’;
btn1.style.color = ‘white’;
btn2.style.color = ‘white’;
btn1.textContent = ‘Start’;
btn2.textContent = ‘Stop’;

Set up a global object that can be used to hold the full start and stop times. The object named game can be selected within the code as its global, and can have property values set since it’s an object. The game timer can be used to hold the interval for the update of the time display.

const game = {timer:null,start:null,end:null};

Add the event listeners to the buttons. Disable the stop button so there is only one option. Below the code will add them as event listeners, listening for the click on the button.

btn1.addEventListener(‘click’,startTimer);
btn2.addEventListener(‘click’,endTimer);
btn2.disabled = true;

Set up the functions to start and stop the timer. Toggle the buttons to be disabled for the start, so it cannot be clicked again. And the stop should be enabled. Get the current new Date() value, then get the value of the getTime() which will return the time in milliseconds since the ECMAScript epoch. (which is defined as January 1, 1970, UTC)

function startTimer(){
btn1.disabled = true;
btn2.disabled = false;
const date = new Date();
game.start = date.getTime();
}

Set up the function to stop the timer. Toggle the buttons to be disabled and enabled. Get the current date and set the end time. You can calculate the amount of time passed by subtracting the game.start time from the game.end time. Divide by 1000 for seconds. Add in a condition to check if the game.timer is set that it will clear the interval variable with the name game.timer.

function endTimer(){
btn1.disabled = false;
btn2.disabled = true;
const date = new Date();
game.end = date.getTime();
const totalTime = ((game.end-game.start)/1000);

if(game.timer){
clearInterval(game.timer);
}
}

Adding the display can be done with a function that will calculate the time passed on a set interval. Create a function named showTimer() and add it to be invoked on the start button click.
Within the showTimer() function declare variables for minutes, seconds, and milliseconds. Set a game.timer object with the setInterval(). Update every 10 milliseconds.
Get the current time, and subtract the start time. This will give a value in milliseconds as to how long the timer is running. Since the minutes is the largest time value, get the minutes removing the seconds and milliseconds by dividing them from the difference.
Update the minutes to add an extra zero if the value is less than 10.
Get the value of seconds, by dividing the difference. If the value of the seconds is greater than 60, then get the modulus remainder using %=. Update the extra 0 with a condition.
Get the milliseconds by using the %= which will return the remainder of the value once divided by 1000.
Output the values for the visible display to the user.

function showTimer(){
let mins,secs,millis;
game.timer = setInterval(()=>{
const diff = new Date().getTime() – game.start;
mins = parseInt(diff/1000/60);
mins = mins < 10 ? ‘0’+mins : mins; secs = parseInt(diff/1000); if(secs>60) secs %= 60;
secs = secs < 10 ? ‘0’+secs : secs; millis = diff; if(millis>1000) millis %= 1000;
timer.textContent = ${mins}:${secs}:${millis};
},10);
}

Final source code below

const main = document.querySelector(‘.main’);
const timer = document.createElement(‘div’);
const btn1 = document.createElement(‘button’);
const btn2 = document.createElement(‘button’);

const game = {timer:null,start:null,end:null};

main.append(timer);
main.append(btn1);
main.append(btn2);
btn1.style.backgroundColor = ‘green’;
btn2.style.backgroundColor = ‘red’;
btn1.style.color = ‘white’;
btn2.style.color = ‘white’;
btn1.textContent = ‘Start’;
btn2.textContent = ‘Stop’;
btn2.disabled = true;
btn1.addEventListener(‘click’,startTimer);
btn2.addEventListener(‘click’,endTimer);

function startTimer(){
console.log(‘start’);
showTimer();
btn1.disabled = true;
btn2.disabled = false;
const date = new Date();
game.start = date.getTime();
}
function endTimer(){
console.log(‘end’);
btn1.disabled = false;
btn2.disabled = true;
const date = new Date();
game.end = date.getTime();
const totalTime = ((game.end-game.start)/1000);
console.log(totalTime);
if(game.timer){
clearInterval(game.timer);
}
}

function showTimer(){
let mins,secs,millis;
game.timer = setInterval(()=>{
const diff = new Date().getTime() – game.start;
mins = parseInt(diff/1000/60);
mins = mins < 10 ? ‘0’+mins : mins; secs = parseInt(diff/1000); secs = secs < 10 ? ‘0’+secs : secs; if(secs>60) secs %= 60;
millis = diff;
if(millis>1000) millis %= 1000;
timer.textContent = ${mins}:${secs}:${millis};
},10);
}