2021年1月27日星期三

now.getTime() inside useEffect doesn't work

I wanted to record how many time passed until user click the button. My plan was like: (the time when user enter the page) - (the time when user click the button) = how many milliseoconds passed!

but my code had an bug and error. my useEffect didn't go what I wanted.. It didn't memorized the time when user entered the page.

console said :

👉undefined

and when first hit:

-1611798597788milliseconds passed

(it worked well as I planned when second hit. weird 🤔)

here's my code:

const UserTimer = () => {    const [startTime, setStartTime] = useState(null);    const [endTime, setEndTime] = useState(0);    const [diff, setDiff] = useState(0);      useEffect(() => {      let now = new Date();      setStartTime(now.getTime());      console.log('👉' + startTime);    }, []);      const onClick = () => {      setEndTime(Date.now());      setDiff(endTime - startTime);      setStartTime(endTime);    };      return (      <div>        <p>{diff}milliseconds passed</p>        <button onClick={onClick}>click here</button>      </div>    );  };  

thank you in advance.

https://stackoverflow.com/questions/65929962/now-gettime-inside-useeffect-doesnt-work January 28, 2021 at 09:56AM

没有评论:

发表评论