next.js 我的NextJS计时器没有停止,变成了负数,我该如何修复这个问题?

k10s72fa  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(141)

下面是我的计时器的代码。我从数据库中得到了“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;

谢谢你!

esbemjvw

esbemjvw1#

我认为,要有效地停止您的计时器,您应该将Ref.current = id;设置为null
尝试在启动计时器时将Ref.current设置为setInterval

Ref.current = setInterval(() => {
     startTimer(e);
}, 1000)

然后停止并清除Interval

const clearTimer = (e) => {
  if (Ref.current) clearInterval(Ref.current);
      Ref.current = null;
      setTimer('00:00:00');
}

应该可以!

相关问题