From a7905ddd1674d3bb00285d7d2f4701d28192fff5 Mon Sep 17 00:00:00 2001 From: codex Date: Wed, 10 Jun 2026 20:01:52 +0200 Subject: [PATCH] Apply latest YouTube state after player readiness --- public/app.js | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/public/app.js b/public/app.js index fc1f3c0..3dbe71f 100644 --- a/public/app.js +++ b/public/app.js @@ -46,6 +46,8 @@ let currentYoutubeVideoId = ""; let applyingWatchStateUntil = 0; let pauseEnforcementUntil = 0; let desiredYoutubePlaying = false; +let pendingWatchState = null; +let pendingWatchStateOptions = null; let watchPlaylist = []; const peers = new Map(); @@ -292,6 +294,13 @@ async function ensureYoutubePlayer() { events: { onReady: () => { youtubeReady = true; + if (pendingWatchState) { + const state = pendingWatchState; + const options = pendingWatchStateOptions || {}; + pendingWatchState = null; + pendingWatchStateOptions = null; + applyWatchState(state, options).catch(console.error); + } }, onStateChange: handleYoutubeStateChange } @@ -300,7 +309,7 @@ async function ensureYoutubePlayer() { } function requestYoutubePlayback(player) { - for (const delay of [0, 150, 750, 1500, 3000]) { + for (const delay of [0, 150, 750, 1500, 3000, 5000]) { setTimeout(() => { if (desiredYoutubePlaying) player.playVideo(); }, delay); @@ -427,11 +436,14 @@ async function applyWatchState(state, { suppressEvents = true } = {}) { if (shouldPlay) { const sameVideo = player.getVideoData?.().video_id === currentYoutubeVideoId; const playerState = player.getPlayerState?.(); - if (sameVideo && playerState === YT.PlayerState.PLAYING) { + if (sameVideo) { player.seekTo(position, true); } else { player.loadVideoById(currentYoutubeVideoId, position); } + if (playerState !== YT.PlayerState.PLAYING) { + player.playVideo(); + } requestYoutubePlayback(player); } else { if (player.getVideoData?.().video_id !== currentYoutubeVideoId) { @@ -452,11 +464,8 @@ async function applyWatchState(state, { suppressEvents = true } = {}) { }, 2500); } } else { - const interval = setInterval(() => { - if (!youtubeReady) return; - clearInterval(interval); - applyWatchState(state, { suppressEvents }).catch(console.error); - }, 100); + pendingWatchState = state; + pendingWatchStateOptions = { suppressEvents }; } }