Created
October 22, 2023 04:38
-
-
Save farhadjaman/71cd39941e9d4ba1d2e0ec65b7de53be to your computer and use it in GitHub Desktop.
Track time between state transtiion using Date function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
import VideoPlayer from './VideoPlayer'; // Import your VideoPlayer component | |
const Create = () => { | |
const [watchVideo, setWatchVideo] = useState(false); | |
const [startTime, setStartTime] = useState(null); | |
const [elapsedTime, setElapsedTime] = useState(0); | |
useEffect(() => { | |
let interval; // Store the interval ID | |
if (watchVideo) { | |
// Start the timer when the video is opened | |
setStartTime(Date.now()); | |
// Check every 2 seconds whether the video is still open | |
interval = setInterval(() => { | |
if (!watchVideo) { | |
// Video is no longer open, so stop the timer | |
clearInterval(interval); | |
if (startTime) { | |
const currentTime = Date.now(); | |
const elapsed = Math.floor((currentTime - startTime) / 1000); // Calculate elapsed time in seconds | |
setElapsedTime(elapsed); | |
setStartTime(null); // Reset the start time | |
} | |
} | |
}, 2000); // Check every 2 seconds (2000 milliseconds) | |
} | |
// Clean up the interval when the component unmounts | |
return () => { | |
if (interval) { | |
clearInterval(interval); | |
} | |
}; | |
}, [watchVideo, startTime]); | |
return ( | |
<div> | |
<button onClick={() => setWatchVideo(true)}>Open Video</button> | |
<button onClick={() => setWatchVideo(false)}>Close Video</button> | |
<VideoPlayer | |
url="/skill-sessions.mp4" | |
playing | |
openOnModal | |
isModalOpen={watchVideo} | |
closeModalHandler={() => setWatchVideo(false)} | |
/> | |
{watchVideo && <p>Elapsed Time (in seconds): {elapsedTime}</p>} | |
</div> | |
); | |
}; | |
export default Create; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment