Q:

setTimeout animation not working

I am trying to animate a square fading into a canvas element. When I use setInterval for my animation, everything works fine, but if I try to use setTimeout, everything falls apart. Here is my code:
http://jsbin.com/OyiRIVa/1/edit
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                              window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
/*class canvasUiElement*/
function canvasUiElement() {}
canvasUiElement.prototype = {
    canvas: document.getElementById("canvas"),
    context: canvas.getContext("2d")
}
/* ---------------------*/
function rectangle(x,y,length,width){
    this.x = x;
    this.y = y;
    this.opacity = 0  ;
    this.length = length;
    this.width = width;
}
rectangle.prototype = new canvasUiElement();
rectangle.prototype.renderSelf = function(){
    this.context.clearRect(this.x,this.y,this.length,this.width);
    this.context.fillStyle = "rgba(0,0,255,".concat(this.opacity.toString().concat(")"));
    this.context.fillRect(this.x,this.y,this.length,this.width);
}
rectangle.prototype.drawFrame = function(){
    this.opacity += .01;
    this.renderSelf();
    x = this.drawFrame;
    setTimeout(function(){x()}, 5); 
}
rect = new rectangle(20,10,50,50);
rect.drawFrame();
/*window.setInterval(function() {
    rect.drawFrame();
}, 1); */

A:

The problem probably lies in the this keyword in drawFrame. When the setTimeout fires, this in side is no longer rect.
The solution is using apply or call.
f.apply(self) bind the this keyword in function f to the first argument f.
So change this way:
rectangle.prototype.drawFrame = function draw(){
  var self = this;
  this.opacity += 0.005;
  this.renderSelf();
  if (this.opacity < 1) {
    requestAnimationFrame(function(){
      draw.call(self)
    });
  }
};

check out this JSBin. http://jsbin.com/OwaHALUF/4/edit
========================
edited upon a valid comment:

x in the original code is not semantic and misses var declaration. Fixed.
prefer requestAnimationFrame to setTimeout
stop call drawFrame if opacity >= 1 (useful if requestAnimationFrame is not availlable)
prefer named function expression over re-assignment. It reduces closure overhead.(This overhead may be not neglected if the animation lasts long enough). And more concise code is bonus.

