Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从当前日期开始倒计时至5分钟_Javascript_Reactjs_React Hooks_Countdown_Countdowntimer - Fatal编程技术网

Javascript 从当前日期开始倒计时至5分钟

Javascript 从当前日期开始倒计时至5分钟,javascript,reactjs,react-hooks,countdown,countdowntimer,Javascript,Reactjs,React Hooks,Countdown,Countdowntimer,这里有新的反应。 我正在尝试输出一个倒计时计时器到一个从现在起设置为5分钟的日期。但我所能得到的不是倒计时橡皮筋,就是5分钟或0分钟的静电。目前,它在00:00:00:00是静态的。谢谢 编辑:我试图让它与钩子一起工作,而不是通过构造函数类 从“./AButton”导入AButton; 从“react”导入{useState,useRef,useffect} export default function Countdown() { const [addTime

这里有新的反应。 我正在尝试输出一个倒计时计时器到一个从现在起设置为5分钟的日期。但我所能得到的不是倒计时橡皮筋,就是5分钟或0分钟的静电。目前,它在00:00:00:00是静态的。谢谢

编辑:我试图让它与钩子一起工作,而不是通过构造函数类

从“./AButton”导入AButton; 从“react”导入{useState,useRef,useffect}

export default function Countdown() {
        
        const [addTime, setAddtime] = useState();
        const [countdown, setCountdown] = useState((new Date()).toLocaleTimeString());

        const [timerDays, setDays] = useState('00');
        const [timerHours, setHours] = useState('00');
        const [timerMinutes, setMinutes] = useState('00');
        const [timerSeconds, setSeconds] = useState('00');

        let interval = useRef();

        const oldDateObject = new Date();
        const sourceDate = oldDateObject.getTime(); // date - 300000
        const diff = 5;
        //this gives use the unix timestamp of the future date which is the current date + 5 minutes
        const futureDate = new Date(oldDateObject.getTime() + diff*60000); //300000
        

        const convertToDate = (date, hours, minutes, seconds) => {
                
        
        date = new Date(sourceDate * 1000);
        // Hours part from the timestamp
        hours = date.getHours();
        // Minutes part from the timestamp
        minutes = ("0" + date.getMinutes()).substr(-2);
        // Seconds part from the timestamp
        seconds = ("0" + date.getSeconds()).substr(-2);

        return hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
        }

        const startTimer = () => {
                const timeUpdate = new Date().getTime(convertToDate);
        interval = setInterval(() => {  
        const now = new Date().getTime();
        const timeDifference = timeUpdate - now;
        
        //this converts the unix code of the future date to each clock element every second
        const days = Math.floor(timeDifference / (24 * 60 * 60 * 1000));
        const hours = Math.floor(timeDifference % (24 * 60 * 60 * 1000) / (60 * 60 * 1000));;
        const minutes = Math.floor(timeDifference % (60 * 60 * 1000) / (60 * 1000));;
        const seconds = Math.floor(timeDifference % (60 * 1000) / 1000);;
        

        if (timeDifference < 0) {
                clearInterval(interval.current);
        } else {
                setDays(days);
                setHours(hours);
                setMinutes(minutes);
                setSeconds(seconds);
        }

        }, 1000);
};

useEffect(() => {
        startTimer();
        return () => { clearInterval(interval.current); 
        };
});
        
        return (
        <div>
        <h1>{countdown === null ? <span style={{padding: '50px'}}></span> : countdown}</h1>
        <button onClick={ () => setCountdown(countdown !== null ? null : ( new Date()).toLocaleTimeString())}>{countdown === null ? 'Show' : 'Hide'}</button>
        <div>----------------</div>
        <h1>{timerDays} : {timerHours} : {timerMinutes} : {timerSeconds}</h1>
        <button>Activate countdown</button>
        </div>
        )
}
导出默认函数倒计时(){
const[addTime,setAddtime]=useState();
const[countdown,setCountdown]=useState((新日期()).toLocaleTimeString());
常数[timerDays,setDays]=useState('00');
常数[timerHours,setHours]=useState('00');
常数[timerMinutes,setMinutes]=useState('00');
常量[timerSeconds,setSeconds]=useState('00');
让interval=useRef();
const oldDateObject=新日期();
const sourceDate=oldDateObject.getTime();//日期-300000
常数差=5;
//这将使用未来日期的unix时间戳,即当前日期+5分钟
const futureDate=新日期(oldDateObject.getTime()+diff*60000);//300000
const convertToDate=(日期、小时、分钟、秒)=>{
日期=新日期(sourceDate*1000);
//时间戳中的小时数部分
小时=date.getHours();
//时间戳中的分钟部分
分钟=(“0”+date.getMinutes()).substr(-2);
//时间戳的秒数部分
秒=(“0”+date.getSeconds()).substr(-2);
返回时数+':'+分钟.substr(-2)+':'+秒.substr(-2);
}
常数startTimer=()=>{
const timeUpdate=new Date().getTime(convertToDate);
间隔=设置间隔(()=>{
const now=new Date().getTime();
常数时差=时间更新-现在;
//这将每秒将未来日期的unix代码转换为每个时钟元素
施工天数=数学下限(时差/(24*60*60*1000));
常数小时=数学楼层(时差%(24*60*60*1000)/(60*60*1000));;
常数分钟=数学楼层(时差%(60*60*1000)/(60*1000));;
常数秒=数学楼层(时差%(60*1000)/1000);;
如果(时差<0){
clearInterval(interval.current);
}否则{
设置日(天);
设定时间(小时);
设置分钟(分钟);
设置秒(秒);
}
}, 1000);
};
useffect(()=>{
startTimer();
return()=>{clearInterval(interval.current);
};
});
返回(
{倒计时===null?:倒计时}
setCountdown(倒计时!==null?null:(新日期()).toLocaleTimeString())}>{countdown==null?'Show':'Hide'}
----------------
{timerDays}:{timerHours}:{timerMinutes}:{timerSeconds}
启动倒计时
)
}
看看


我认为你让事情变得比实际需要的更复杂了

存储5分钟倒计时状态(以秒为单位)和启动/运行计时器的第二个状态

计时器启动时,将倒计时状态设定为5分钟(它将从当前时间点过期)

计算从单个倒计时状态导出并格式化的时间

函数应用程序(){
const[countDown,setCountDown]=React.useState(0);
const[runTimer,setRunTimer]=React.useState(false);
React.useffect(()=>{
让时光流逝;
if(运行计时器){
设置倒计时(60*5);
timerId=setInterval(()=>{
设置倒计时((倒计时)=>倒计时-1);
}, 1000);
}否则{
清除间隔(timerId);
}
return()=>clearInterval(timerId);
},[runTimer]);
React.useffect(()=>{
if(倒计时<0&&runTimer){
控制台日志(“过期”);
setRunTimer(假);
设置倒计时(0);
}
},[倒计时,运行计时器];
const-togglerTimer=()=>setRunTimer((t)=>!t);
常数秒=字符串(倒计时%60)。padStart(2,0);
const minutes=String(数学楼层(倒计时/60)).padStart(2,0);
返回(
时间:{分钟}:{秒}
{runTimer?“Stop”:“Start”}
);
}
const rootElement=document.getElementById(“根”);
ReactDOM.render(
,
根元素
);
.App{
字体系列:无衬线;
文本对齐:居中;
}


谢谢你,伙计,我试着用钩子而不是包或构造函数类来实现它。谢谢你的回答,我理解逻辑的速度仍然很慢,所以我需要一些时间来阅读它。虽然,从另一方面来说,我想我理解了我的错误,我希望既能输出倒计时即将结束的日期,又能使用日期中的数字来激活倒计时。太棒了,这对我来说应该很好,但如果你不介意的话,我确实有两个问题:-第一,为什么没有;您是否对timerId变量使用useRef(),以及-小时和天的数学是什么样的?@T888我没有对计时器使用ref是因为计时器id在
useffect
回调函数的作用域中完全关闭。它不需要被效果回调外部的任何东西引用。对于计算日、时、分和秒,数学有点不同(嗯,基本相同,只是更多)。检查这个。这能回答你的问题吗?