How to pause a YouTube video at a specific timestamp

I’ve been trying to figure out how to automatically stop a YouTube video when it reaches a particular time. I know you can set a start time, but I can’t seem to find a way to make it pause at a specific point.

Is there a method to do this that I’m missing? Or maybe a clever workaround? I’ve looked through the YouTube API docs, but I might have overlooked something.

If anyone has experience with this, I’d really appreciate some help. It seems like a simple thing, but it’s giving me a headache!

Here’s a basic example of what I’m trying to do:

function playVideo() {
  const player = new YT.Player('video-container', {
    videoId: 'dQw4w9WgXcQ',
    events: {
      onReady: (event) => {
        event.target.playVideo();
      },
      onStateChange: (event) => {
        if (event.data == YT.PlayerState.PLAYING) {
          // How do I pause at 30 seconds?
        }
      }
    }
  });
}

Any ideas on how to make this work?

I’ve tackled this issue before in a project. The key is to use the getCurrentTime() method and check it against your desired pause time in the onStateChange event. Here’s how you can modify your code:

function playVideo() {
  const player = new YT.Player('video-container', {
    videoId: 'dQw4w9WgXcQ',
    events: {
      onReady: (event) => {
        event.target.playVideo();
      },
      onStateChange: (event) => {
        if (event.data === YT.PlayerState.PLAYING) {
          const checkTime = setInterval(() => {
            if (player.getCurrentTime() >= 30) {
              player.pauseVideo();
              clearInterval(checkTime);
            }
          }, 100);
        }
      }
    }
  });
}

This sets up an interval that checks the current time every 100ms. When it reaches or exceeds 30 seconds, it pauses the video and clears the interval. Adjust the time check and interval as needed for your specific use case.