title: Youtube iframe javascript, track percentage of video watched?
body: <p>I am trying to get an accurate calculation of how much time a user has spent watching a video. The time they spent watching it should not include skipping forward or when the video is paused. The code I have now is giving me a different percentage each time (I'm using an interval). I don't know how else to go about this? </p>
  
  <pre><code>function onPlayerStateChange(event) {
      if (event.data == YT.PlayerState.PLAYING &amp;&amp; !done) {
        clicked_video = true; 
        arr.length = (player.getDuration()-1).toFixed(0);
        done = true;
  
      }if(event.data === YT.PlayerState.PLAYING){
  
         id = setInterval(check, 1000);
  
     }if(event.data == YT.PlayerState.PAUSED || event.data == YT.PlayerState.BUFFERING){
  
          clearInterval(id);
          var percent = 0;
          for(var i=0;i&lt;arr.length;i++){
            if(arr[i] == "x"){
            percent++;
            console.log(percent);
            }
  
         }
  
      percent = (percent / arr.length) * 100;
      alert(percent + "%");
      }
  }
  function check(){
  
        arr[Math.floor(player.getCurrentTime())] = "x";
  }
  </code></pre>