下面是我的计时器的代码。我从数据库中获取了 'createdAt' 属性,一切正常。然而,当达到 0 时,计时器不会停止,而是继续计时。我尝试添加
if (total < 0) {setTimer("00:00:00)}
但这似乎不起作用。
如果您还有任何其他问题,请告诉我。
如有任何帮助,我们将不胜感激。
代码:
import { create } from 'domain';
import React, { useState, useRef, useEffect } from 'react'
const Timer = ({time, createdAt}) => {
// We need ref in this, because we are dealing
// with JS setInterval to keep track of it and
// stop it when needed
const Ref = useRef(null);
// The state for our timer
const [timer, setTimer] = useState('00:00:00');
const [timerOn, setTimerOn] = useState(false)
const number = 1000
const getTimeRemaining = (e) => {
var total = (Date.parse(e) - Date.parse(new Date())) / 1000;
var days = Math.floor(total / 86400);
total -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(total / 3600) % 24;
total -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(total / 60) % 60;
total -= minutes * 60;
// what's left is seconds
var seconds = total % 60;
return {
total, days, hours, minutes, seconds
};
}
const startTimer = (e) => {
let { total, days, hours, minutes, seconds }
= getTimeRemaining(e);
if (total >= 0) {
// update the timer
// check if less than 10 then we need to
// add '0' at the beginning of the variable
setTimer(
(days < 1 ? '00' : days) + ':' +
(hours > 9 ? hours : '0' + hours) + ':' +
(minutes > 9 ? minutes : '0' + minutes) + ':'
+ (seconds > 9 ? seconds : '0' + seconds)
)
}
}
const clearTimer = (e) => {
// If you adjust it you should also need to
// adjust the Endtime formula we are about
// to code next
setTimer('00:00:00');
// If you try to remove this line the
// updating of timer Variable will be
// after 1000ms or 1sec
if (Ref.current) clearInterval(Ref.current);
const id = setInterval(() => {
startTimer(e);
}, 1000)
Ref.current = id;
}
const getDeadTime = () => {
let deadline = new Date(createdAt); //get creator date from local storage, store it in a variable/const and set definite timer from there || Get and save creation time in Mongo
// This is where you need to adjust if
// you entend to add more time
deadline.setSeconds(deadline.getSeconds() + Math.floor(time));
return deadline;
}
// We can use useEffect so that when the component
// mount the timer will start as soon as possible
// We put empty array to act as componentDid
// mount only
useEffect(() => {
clearTimer(getDeadTime());
}, []);
const onClickReset = () => {
clearTimer(getDeadTime());
}
// Another way to call the clearTimer() to start
// the countdown is via action event from the
// button first we create function to be called
// by the button
return (
<div className="App">
<h2 className='text-3xl lg:text-4xl text-transparent bg-clip-text text-center bg-gradient-to-r from-pink-500 via-red-500 to-yellow-500'>{timer}</h2>
</div>
)
}
export default Timer;
谢谢!
我认为要有效地停止计时器,您应该将
Ref.current = id;
设置为 null
。
尝试在启动计时器时将您的
Ref.current
设置为您的 setInterval
Ref.current = setInterval(() => {
startTimer(e);
}, 1000)
然后停止并清除间隔
const clearTimer = (e) => {
if (Ref.current) clearInterval(Ref.current);
Ref.current = null;
setTimer('00:00:00');
}
应该可以!
这里如何使用代码示例正确设置它
import React, { useEffect, useRef, useState } from 'react';
function TimerComponent() {
const Ref = useRef(null);
const [timer, setTimer] = useState('00:00:00');
// Start timer on mount
useEffect(() => {
Ref.current = setInterval(() => {
startTimer();
}, 1000);
// Clear timer on unmount
return () => {
if (Ref.current) clearInterval(Ref.current);
Ref.current = null;
setTimer('00:00:00');
};
}, []);
// startTimer() function
const startTimer = () => {
// Your logic here
};
// clearTimer() function
const clearTimer = () => {
if (Ref.current) clearInterval(Ref.current);
Ref.current = null;
setTimer('00:00:00');
};
return (
<div>
<p>{timer}</p>
<button onClick={clearTimer}>Stop Timer</button>
</div>
);
}