0

I have the following code which is being called after the native player.loadNewVideoById function from youtube.

function initSliderAndTime() {

    setTimeout(() => {
        var durationInSeconds = player.getDuration()
    
        $('#time-slider').attr('max', player.getDuration().toString().match(/^-?\d+(?:\.\d{0,1})?/)[0])
    
        $('#end-time')[0].innerText = calculateTimeFormat(durationInSeconds);
        
    }, 1000);

}

If I don't call a time out the player id is undefined and the function ins't doing what it it supposed to do. How can I turn this into an asynchronous function, so that it executes after the player has initialised.

I know about the OnReady Function from youtube's iframe api, but that doesn't get called when the player is updated, only if it created.

Any help is appreciated!

Andy
  • 61,948
  • 13
  • 68
  • 95

1 Answers1

0

I don't have enough sample code to test this answer atm but it should look something like this.

async function initSliderAndTime() {
    let myPromise = new Promise( function( resolve ) {
        resolve( player.getDuration() );
    });
    
    myPromise.then (
        let maxTime = await myPromise;
        
        $('#time-slider').attr('max', maxTime.toString().match(/^-?\d+(?:\.\d{0,1})?/)[0]);
        $('#end-time')[0].innerText = calculateTimeFormat(durationInSeconds);
    );
}

initSliderAndTime();

Maybe an easier more readable format is the try/catch. Either way the key is the async function declaration and the await keyword where the promise will be returned.

async function initSliderAndTime() {
    try {
        let durationInSeconds = await player.getDuration();
        $('#time-slider').attr('max', durationInSeconds.toString().match(/^-?\d+(?:\.\d{0,1})?/)[0]);
        $('#end-time')[0].innerText = calculateTimeFormat(durationInSeconds);
    } catch(error) {
        return null;
    }
}

initSliderAndTime();

Lots more examples here: How to return the response from an asynchronous call

Lucretius
  • 1,053
  • 1
  • 13
  • 26