0

我的页面上有一个计时器,它在 youtube 视频开始后倒计时 10 秒。当计时器完成时,将启用。如果用户在这 10 秒内暂停/恢复视频,我也想暂停和恢复计时器。

我的代码如下所示:

      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('ytvideo', {
          height: '390',
          width: '640',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

      function onPlayerReady(event) {
        event.target.playVideo();
        timerid = setTimeout(enableButtons, 10000)
      }

      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PAUSED) {

            // pause & resume ?

        }
      }

      function enableButtons() {

        document.getElementById("push").disabled = false; 
        document.getElementById("next").disabled = false; 

      }
4

1 回答 1

0

您需要记下开始时间,如果视频暂停,请记下暂停时间,计算经过的时间,并在重新启动时创建一个新setTimeout10000-{previous elapsed time}

希望下面的代码能够很好地演示这一点,以便您与代码集成。这里有很多关于编写演示的“绒毛”——对你有用的部分我会用评论来包围。

var timeId;
var startTime;
var pauseTime;
$('#start').on('click',function(){
  // when your video starts make a note of the time
  startTime = Date.now();
  timerId = setTimeout(complete,10000);

  // Ignore below
  out("The timer is running for 10000ms");
  $('#pause').prop('disabled',false);
  $(this).prop('disabled',true);
});

$('#pause').on('click',function(){
    // When user pauses video, clear the timeout and make a note of pause time
    clearTimeout(timerId);
    pauseTime = Date.now();

    // Ignore below
   out("The timer is paused with " + (10000-(pauseTime-startTime)) + "ms remaining");
  $('#resume').prop('disabled',false);
  $(this).prop('disabled',true);
});

$('#resume').on('click',function(){
   // When user resumes, calculate remaining time and start a new timeout
   var remaining = (10000-(pauseTime-startTime));
   setTimeout(complete,remaining);

   // ignore below
   out("The timer is running for " + remaining + "ms");
  $('#pause').prop('disabled',false);
  $(this).prop('disabled',true);
})

// Ignore below
function complete(){
   out("The timer is complete");
  $('#start').prop('disabled',false);
  $('#pause').prop('disabled',true);
}

function out(msg){
   $('#output').html(msg);  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="pause" disabled>Pause</button>
<button id="resume" disabled>Resume</button>
<div id="output"></div>

于 2015-10-08T10:55:56.443 回答