Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

322
Views
How can I implement async functions in my code?

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!