Home > Software engineering >  How do I display an object from an array based on timer?
How do I display an object from an array based on timer?

Time:02-23

I'm building a music application and I'd like to display content from a specific object in an array based on a start and duration time. Here is an example of my data.

[
{
id: 1,
content: 'hello how are you',
start: 0,
duration: 10
},
{
id: 2,
content: 'hello Im fine',
start: 15,
duration: 10
},
{
id: 3,
content: 'hope you you have a great day',
start: 30,
duration: 10
}
]

So basically I will be using the currentTime property on the audio element, and based on this property I will display the appropriate message on content property. Currently I've been able to match the content start with the currentTime, but unable to figure out how to display over the duration. This is pretty much what I have:

const PodcastDetail = ({ podcast }) => {
    const [currentMarker, setCurrentMarker] = useState({});
}

  const handleMarker = (podcast) => {
        let marker = podcast.markers.find((mark) => {
            return mark.start  == currentTime;
        })
        setCurrentMarker(marker)
    }

As you can see I'm just returning the object from the array which matches the current time, however it disappears once the currentTime changes. I'd like to display that content throughout its duration.

CodePudding user response:

however it disappears once the currentTime changes.

It's because you just change your state with a null (no object found) :) You can basically do something like that:

const handleMarker = (podcast) => {
    let marker = podcast.markers.find((mark) => {
        return mark.start  == currentTime;
    })
    if (marker) setCurrentMarker(marker)
}

So if no marker match your currentTime, you don't update the state, so you leave the previous marker in your state

== EDIT ==

And if you want to use your duration you should change your condition to

const handleMarker = (podcast) => {
    let marker = podcast.markers.find((mark) => {
        return (currentTime >= mark.start) && (currentTime <= (mark.start   mark.duration));
    })
    setCurrentMarker(marker)
}

In this case I remove the condition to setCurrentMarker because you indeed want to set it at null if nothing matches the condition

CodePudding user response:

You should change the condition to check whether it is within the interval as well.

const handleMarker = (podcast) => {
  let marker = podcast.markers.find((mark) => {
    return (
      mark.start <= currentTime && currentTime <= mark.start   mark.duration
    );
  });
  setCurrentMarker(marker);
};
  • Related