Take some time to understand the following example program.
The system clock functions as you expect, and we simply make reference to it.
Counting months can be challenging due to the varying number of days in each month (28, 29, 30, or 31).
popup.js
const elmCounter = document.getElementById("counter");
const elmReset = document.getElementById("reset");
let lastTime = localStorage["lastTime"];
if (lastTime == null) {
lastTime = new Date();
localStorage["lastTime"] = lastTime;
}
else {
lastTime = new Date(lastTime);
}
counter();
elmReset.onclick = () => {
lastTime = new Date();
localStorage["lastTime"] = lastTime;
};
async function counter() {
while (1) {
const nowTime = new Date();
let diffTime = nowTime.getTime() - lastTime.getTime();
diffTime /= 1000;
diffTime = Math.floor(diffTime);
const day = Math.floor(diffTime / (24 * 60 * 60));
diffTime -= day * 24 * 60 * 60;
const hour = Math.floor(diffTime / (60 * 60));
diffTime -= hour * 60 * 60;
const min = Math.floor(diffTime / 60)
const sec = diffTime % 60
elmCounter.innerText = day + "," + hour + "," + min + "," + sec;
await new Promise(r => setTimeout(r, 500));
}
}
manifest.json
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "popup.html"
}
}
popup.html
<!DOCTYPE html>
<head>
<style type="text/css">
* {
font-size: xx-large;
}
</style>
</head>
<body style="min-width:250px;min-height:100px">
<div id="counter"></div><br>
<input type="button" id="reset" value="reset">
<script src="popup.js"></script>
</body>
</html>