Skip to content
Advertisement

Why doesn’t the video stop when the “currentTime>=maxTime” in Javascript?

Look at this code

I tried to play the video from a specific time to another specific time.

<html>
<head>

<script>
function playVideo(str) { 
  var video = document.getElementById("myVideo");
  video.src = str;
  video.currentTime=16;
  video.play();

  var maxTime = 20;
  video.addEventListener("progress", function(){
    if(video.currentTime >= maxTime){
     video.pause();  
    }
  }, false);
} 

</script>
</head>
<body>


<video id="myVideo" width="1000" height="800" controls autoplay loop>

  Your browser does not support the video tag.
</video>


<a  onclick="playVideo('video/journey27.mp4')" > Play2 </a>

</body>
</html>

Why doesn’t the video stop when the currentTime>=maxTime?

i think there is something wrong with the eventListener.

Advertisement

Answer

You need to use the “timeupdate” event listener that executes whenever the time changes and not the progress which run on different situations.

Your playVideo function should look something like this:

function playVideo(str) {
  var video = document.getElementById("myVideo");
  video.src = str;
  video.currentTime = 16;
  video.play();

  var maxTime = 20;
  video.addEventListener(
    "timeupdate", // changed the event listener
    function (event) {
      if (this.currentTime >= maxTime) {
        video.pause();
      }
    },
    false
    );
  }

Worth to mention that using an instance of the object that you’re creating an event listener to him is not always a best practice and better to use this key word.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement