Reputation: 19
I'm learning how to dev and I'm trying to implement a stopwatch to my html body using Javascript
var c = 0.0;
function tempo() {
document.getElementById("test").innerHTML = c += 0.1;
}
<button onClick="myTimer = setInterval(tempo, 1000)">Lancement!</button>
<p id="test">Clic ici</p>
<button onClick="clearInterval(myTimer)">Arret!</button>
But is there any function or method to increment the seconds, minutes and hours automatically? Or do I have to count with setInterval
?
edit: its what i'm actually doing ! taking time when click on a button and when click again get the interval between both click...
<button onclick="test()">ICI</button>
let debut;
let fin;
let ouiNon = false;
function test() {
let currentTime = new Date();
let currentSec = currentTime.getSeconds();
let currentMin = currentTime.getMinutes();
let currentHour = currentTime.getHours();
if (ouiNon == false) {
debut = currentTime;
ouiNon = true;
console.log("debut ok");
console.log(debut);
} else {
fin = currentTime;
ouiNon = false;
console.log("fin ok");
console.log(fin);
}
console.log(fin - debut);
}
Upvotes: 1
Views: 159
Reputation: 994
You can use date to get second, minute and hour.
var date = new Date();
date.getSeconds(); //get seconds
date.getMinutes(); //get mintes
date.getHours(); //get hours
but to check this you need setInterval method also.
Upvotes: 1
Reputation: 500
You can use the current time and extract the parts you want from it.
var currentTime = new Date();
var currentSec = currentTime.getSeconds();
var currentMim = currentTime.getMinutes();
var currentHour = currentTime.getHours();
Upvotes: 0