Question

A previous question I asked has got me half way to where I need to be, I now have 1 function that fires off 2 functions. A 'loader' function (a spinner graphic) and playAudio which play a file.

   function loadPlay(src, trackName) {
       loader();
       playAudio(src, trackName);
   }

When a play button is clicked the load spinner is supposed to appear and when the audio plays the spinner should go away.

Play button:

<span class="play"  onclick="loadPlay('http://a797.phobos.apple.com/us/r30/Music/72/89/b9/mzi.aytblawp.aac.p.m4a','t3')"  id="t3">

But what is happening is after the play button is clicked there is a slight pause (as audio loads) and the audio and spinner appear at the same time? The loader should appear as the track loads and then go away when the audio plays?

How do I add a pause to make sure the loader appears BEFORE the audio plays?

Both Functions:

function loader() {
        // make a loader spinner appear as track loads
    $(".loading").addClass("loadingnow");
}

function playAudio(src,trackname) {
    // for Android
    if (audioPlaying === false) {
        if (device.platform == 'Android') {
            src = '/android_asset/www/' + src;
        }
        media = new Media(src, success, error_error);
        media.play();
        //add playing class so play button is replaced with stop button
        document.getElementById(trackname).parentNode.className="playing";
        // now track is playing remove the loader spinner
        $(".loading").removeClass("loadingnow");
        audioPlaying = true;
    } else {
        //audio is already playing
    }
}

function success() {
    // track has finished playing so remove the stop button put play button back
    $(".playing").removeClass("playing");

    audioPlaying = false;
}

function error_error(e) {
    //alert('great error');
    //alert(e.message);
}

function stopAudio() {
    // stop playing track
    if (media) {
        media.stop();
        audioPlaying = false;
    }
}
Was it helpful?

Solution

You can use setTimeout to force jQuery to wait a amount of milliseconds

function loadPlay(src, trackName) {
       loader();
       setTimeout(function(){
              playAudio(src, trackName);
       }, 1000);
}

This will force the playAudio to wait for 1 second. Your loader will pop up, but your user will have to wait for an additional second because of this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top