Здравствуйте, я верстальщик который решил идти дальше в js, сделал секундомер с сохранением значения в localstorage, каким образом сделать несколько независимых секундомеров?
Код ниже
document.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('timerRunning') === 'true')
startTimer();
else
displayTime(parseInt(localStorage.getItem('timestamp')));
});
let timer;
let startTimestamp = parseInt(localStorage.getItem('timestamp'));
function displayTime(timestamp) {
if (timestamp)
display(Date.now() - timestamp);
else
display(0);
}
function startTimer() {
let timestamp = parseInt(localStorage.getItem('timestamp')) || Date.now();
localStorage.setItem('timestamp', timestamp.toString());
localStorage.setItem('timerRunning', 'true');
clearInterval(timer);
timer = setInterval(() => displayTime(timestamp), 100);
}
function stopTimer() {
localStorage.setItem('timerRunning', 'false');
clearInterval(timer);
}
function resetTimer() {
localStorage.removeItem('timestamp');
display(0);
}
function display(milliseconds) {
let el = document.getElementById('timer');
if (el) {
el.innerHTML = msToTime(milliseconds);
}
if (el >= "00:00:00:10") {
document.getElementById('timer').style.background = "green";
document.getElementById('img').style.borderColor = "green";
} else if (el >= "30:00:00:00") {
document.getElementById('timer').style.background = "yellow";
document.getElementById('img').style.borderColor = "green";
} else if (el >= "120:00:00:00") {
document.getElementById('timer').style.background = "red";
document.getElementById('img').style.borderColor = "green";
}
}
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = parseInt((duration / 1000) % 60),
minutes = parseInt((duration / (1000 * 60)) % 60),
hours = parseInt((duration / (1000 * 60 * 60)) % 24),
days = parseInt(duration / (60 * 60 * 1000 * 24));
days = (days < 10) ? "0" + days : days;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return days + ":" + hours + ":" + minutes + ":" + seconds;
}