@@ -12,6 +12,8 @@ import type {
1212import type { SongInfo } from './song-info' ;
1313import type { VideoDataChanged } from '@/types/video-data-changed' ;
1414
15+ const DATAUPDATED_FALLBACK_TIMEOUT_MS = 1500 ;
16+
1517let songInfo : SongInfo = { } as SongInfo ;
1618export const getSongInfo = ( ) => songInfo ;
1719
@@ -253,12 +255,25 @@ export const setupSongInfo = (api: YoutubePlayer) => {
253255 ) ;
254256
255257 const waitingEvent = new Set < string > ( ) ;
258+ const waitingTimeouts = new Map < string , NodeJS . Timeout > ( ) ;
259+
260+ const clearVideoTimeout = ( videoId : string ) => {
261+ const timeoutId = waitingTimeouts . get ( videoId ) ;
262+
263+ if ( timeoutId ) {
264+ clearTimeout ( timeoutId ) ;
265+ waitingTimeouts . delete ( videoId ) ;
266+ }
267+ } ;
268+
256269 // Name = "dataloaded" and abit later "dataupdated"
270+ // Sometimes "dataupdated" is not fired, so we need to fallback to "dataloaded"
257271 api . addEventListener ( 'videodatachange' , ( name , videoData ) => {
258272 videoEventDispatcher ( name , videoData ) ;
259273
260274 if ( name === 'dataupdated' && waitingEvent . has ( videoData . videoId ) ) {
261275 waitingEvent . delete ( videoData . videoId ) ;
276+ clearVideoTimeout ( videoData . videoId ) ;
262277 sendSongInfo ( videoData ) ;
263278 } else if ( name === 'dataloaded' ) {
264279 const video = document . querySelector < HTMLVideoElement > ( 'video' ) ;
@@ -269,7 +284,18 @@ export const setupSongInfo = (api: YoutubePlayer) => {
269284 video ?. addEventListener ( status , playPausedHandlers [ status ] ) ;
270285 }
271286
287+ clearVideoTimeout ( videoData . videoId ) ;
272288 waitingEvent . add ( videoData . videoId ) ;
289+
290+ const timeoutId = setTimeout ( ( ) => {
291+ if ( waitingEvent . has ( videoData . videoId ) ) {
292+ waitingEvent . delete ( videoData . videoId ) ;
293+ waitingTimeouts . delete ( videoData . videoId ) ;
294+ sendSongInfo ( videoData ) ;
295+ }
296+ } , DATAUPDATED_FALLBACK_TIMEOUT_MS ) ;
297+
298+ waitingTimeouts . set ( videoData . videoId , timeoutId ) ;
273299 }
274300 } ) ;
275301
0 commit comments