Chapter 4, Exercise 2 – Amended Bubble Animations

Bubble animations currently consist of four frames. Create your own versions of the images and try adding more frames. Use a for loop to generate the extra setTimeout calls rather than copying and pasting new lines. Experiment with the timeout delays to speed up and slow down the animation and see which values produce the best effect.

I’ll leave you to make your own image with more frames, but one way of refactoring the existing code in bubble.js to accept a variable frame number is as follows:

this.animatePop = function(){
  var top = type * that.getSprite().height();
  this.getSprite().css(Modernizr.prefixed("transform"),"rotate(" + (Math.random() * 360) + "deg)");
  var numFrames = 3;
  for(var i=0;i<numFrames;i++){
    (function(i){
      setTimeout(function(){
        that.getSprite().css("background-position","-" + ((i+1) * 50) + "px -" + top + "px");
      },125 + i*25);
    })(i);
  }
  setTimeout(function(){
    that.getSprite().remove();
  },125 + i*25);
}
Notice how the setTimeout has to be wrapped in a function. if we had simply written:
for(var i=0;i<numFrames;i++){
  setTimeout(function(){
    that.getSprite().css("background-position","-" + ((i+1) * 50) + "px -" + top + "px");
  },125 + i*25);
}

Then the value of i used within the setTimeout would be the final value i.e. 4 (the value that causes the for loop to end) due to closure. By wrapping the timeout in a function and passing the value of i into it we create a new variable scope and the setTimeout function remembers the value of i at the time the function was created.

Leave a Reply

Your email address will not be published. Required fields are marked *