title: Javascript function to detect different keyframes of videos
body: <p>I am developing a simple app where you can live compare two videos. A requirement for this project is that they are perfectly synced. I've done lots of research, and tried almost every single loaded event I could find over Stack Overflow, but no success. I have a new idea, I don't know if this is achievable with Javascript. First of all, here is my code:</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;video id="leftVideo" src="before.mp4" oncanplaythrough="leftVideoLoaded()" alt="before" loop="true" width="600" height="366"&gt;&lt;/video&gt;
  &lt;video id="rightVideo" src="after.mp4" oncanplaythrough="rightVideoLoaded()" alt="after" loop="true" width="600" height="366"&gt;&lt;/video&gt;
  </code></pre>
  
  <p>JS:</p>
  
  <pre><code>var leftVideoLoadedCheck = 0;
  var rightVideoLoadedCheck = 0;
  function leftVideoLoaded() {
      leftVideoLoadedCheck = 1;
  }
  
  function rightVideoLoaded() {
      rightVideoLoadedCheck = 1;
  }
  
  $(document).ready(function() {
      $("#container").beforeAfter();
  
      var leftPlayer = new MediaElement("leftVideo");
      var rightPlayer = new MediaElement("rightVideo");
  
      var refreashLoadedEvent = setInterval(function(){
          if(leftVideoLoadedCheck == 1 &amp;&amp; rightVideoLoadedCheck == 1) {
  
              setTimeout(function() {
                  leftPlayer.play();
                  rightPlayer.play();
              }, 1000);
  
              clearInterval(refreashLoadedEvent);
          }
      }, 50);
  });
  </code></pre>
  
  <p>Here is a live demo:</p>
  
  <p><a href="http://amarsyla.com/sandbox/beforeafter/" rel="nofollow">http://amarsyla.com/sandbox/beforeafter/</a></p>
  
  <p>I got some good results, but if the videos keep looping a few times, they lose their syncing between them. Is there a way I can setup a function which runs every 500ms, and detects the keyframes of each video. When the keyframes are not the same, pause both videos, and start playing them again at one same keyframe. So, I am seeking for something like this:</p>
  
  <pre><code>setInterval(function() {
      firstVideoKeyframe = ...
      secondVideoKeyframe = ...
  
      if(firstVideoKeyframe != secondVideoKeyFrame) {
          firstVideo.pause();
          secondVideo.pause();
  
          var keyframeToPlay = Math.min(firstVideoKeyframe, secondVideoKeyframe);
  
          firstVideo.playAtKeyframe(keyframeToPlay);
          secondVideo.playAtKeyframe(Math.min(keyframeToPlay));
      }
  }, 500);
  </code></pre>
  
  <p>I hope that's not something that only my imagination can do...</p>
  
  <p>Thanks a lot.</p>