Недавно я создал код для отображения обратного отсчета в течение заданных минут и установки значения с помощью предоставленной функции. Вы можете попробовать этот код;
const countdown = (durationInMin, setter) => {
// added 1 second to start time, so this will start from 00 seconds
let startTime = Date.now() + 1000
let diff, min, sec
//updating timer by 1 second
let timer = setInterval(() => {
if (diff <= 0) {
//once the different reached zero, clearing the interval
clearInterval(timer)
return;
}
diff = durationInMin * 60 - (((Date.now() - startTime) / 1000) | 0)
min = (diff / 60) | 0
sec = (diff % 60) | 0
// formatting to two digits
min = min < 10 ? "0" + min : min
sec = sec < 10 ? "0" + sec : sec
// display format
let t = min + ":" + sec
// calling the setter function by passing the timer value
setter(t)
}, 1000)
}
Здесь вы можете указать длительность в минутах для функций durationInMin
и setter
, чтобы отобразить возвращаемое значение из таймера.
Вы можете вызвать с помощью этого как следует;
function setter(value) {
myGlobalVariable = value
}
startTimer() {
countdown(5,setter);
}
Дополнительные ссылки: Я ссылался на этот код из следующей темы StackOverflow
Редактировать:
Поскольку вы предоставили код, вы можете попробовать следующее;
рендер. js
const countdown = (durationInMin, setter) => {
// added 1 second to start time, so this will start from 00 seconds
let startTime = Date.now() + 1000
let diff, min, sec
//updating timer by 1 second
let timer = setInterval(() => {
if (diff <= 0) {
//once the different reached zero, clearing the interval
clearInterval(timer)
return;
}
diff = durationInMin * 60 - (((Date.now() - startTime) / 1000) | 0)
min = (diff / 60) | 0
sec = (diff % 60) | 0
// formatting to two digits
min = min < 10 ? "0" + min : min
sec = sec < 10 ? "0" + sec : sec
// display format
let t = min + ":" + sec
// calling the setter function by passing the timer value
setter(t)
}, 1000)
};
function setter(value) {
var t = document.getElementsByClassName("timer")[0]
t.innerText = value.toString()
}
function startTimer() {
console.log("clicked")
countdown(0.5, setter)
}
index. html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<button onclick="startTimer()">Start Timer</button>
<div class="timer">--:--</div>
<script src="./renderer.js"></script>
</body>
</html>