Skip to main content
Tweeted twitter.com/#!/StackCodeReview/status/606106647048634369
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Source Link
user348173
  • 471
  • 2
  • 11

A Nightmare on setTimeout Street

I have script which plays audio, shows/hides elements:

   var audio = new Audio("audio/test.mp3");

    audio.addEventListener("ended", function(){ 
             element.fadeIn(0);
             setTimeout(function() {
                element2.fadeIn(0);
                setTimeout(function() {
                    element3.fadeIn();
                    sprite.play(); // a one lib for playing sprites
                },1000)
             },1000)
        });

// this is just event and we look for the last frame
sprite.on("frame", function(){
        if(this.frame === this.frames - 1)
        {
            this.pause();           
            setTimeout(function() {
                //here we show some another elements and play another audio
            },1000)
        }
    }); 

audio.play();

As you can see there are a lot of setTimeout and spaghetti code. This is very short version, I have more than 5 audio files and a lot of elements which I have to show and hide, and, it's very difficult to understand the order audio files playing and showing/hiding elements in the end. May be you know how to organize this flow, some libraries? I am a noob at promises, is it good idea here?