HTML5 Video - run events if currentTime equals set time

I am trying to catch certain events while a html5 video is playing. I want to trigger them at the 5, 10, 15, 20 and 25 second marks during playback.

Below is the code that I have running:

this.video.addEventListener('timeupdate', (e) => {
  if (e.target.currentTime >= 5) {
    console.log('5 seconds')
  } else if (e.target.currentTime >= 10) {
    console.log('10 seconds')
  }
})

This seems to work only on the first if statement (currentTime >= 5). It never runs the else if though. When I try and be exact and change >= to a set equal to == it doesn't even run at all.

What am I doing wrong? Any help would be greatly appreciated. I'm also open to other suggestions of a better way to do this.

I'm reading this article and not sure if it's suitable or not: Syncing content with html5 video

Upvotes: 0

Views: 1105

Answers (1)

Colin Cline
Colin Cline

Reputation: 1279

After video crossed the 5th sec , the first statement will always be true because all seconds after 5th are >=5 so it never fall into else. You have 2 approach ahead

1) Use range:

this.video.addEventListener('timeupdate', (e) => {
    if (5 <= e.target.currentTime && e.target.currentTime < 10) {
        console.log('5 seconds')
    } else if (10 <= e.target.currentTime && e.target.currentTime < 25) {
        console.log('10 seconds')
    }
});

2) Do reverse (in placement) if/else

this.video.addEventListener('timeupdate', (e) => {
    if (e.target.currentTime > 25) {
        console.log('25+ seconds')
    } else if (e.target.currentTime > 20) {
        console.log('25-20 seconds')
    } else if (e.target.currentTime > 15) {
        console.log('20-15 seconds')
    }
});

Upvotes: 3

Related Questions