I'm writing a animate method to perform DOM animations. I know there are a lot of libraries out there that already does that (and I use some ideas of them) but I usually prefer writing my own code to pinpoint my problem.
The code below is working perfectly, but something with the structure is making me uncomfortable. I think it is because I use references to itself just before the objects dies, so I'm not sure if I'm reusing the animation object or creating new ones. Apparently there is no memory leak.
Can someone give it a look? Fell free to suggest code modifications even if they are unrelated with the memory leak.
window.animate = function(options) {
var fps = options.fps || 30;
var x = options.x || null;
var y = options.y || null;
var duration = Math.ceil((options.duration / 1000) * fps);
var onProgress = options.onProgress || null;
var onComplete = options.onComplete || null;
var easing = easing || 'easeInOutQuad';
var animation = {
fps: fps,
x: x,
y: y,
duration: duration,
onProgress: onProgress,
onComplete: onComplete,
easing: easing,
_id: null,
_iteration: 1,
_lastFrameOccurrence: 0,
_draw: function() {
var $this = this;
var now = Date.now();
var delta = now - $this._lastFrameOccurrence;
var interval = 1000 / $this.fps;
if (delta > interval) {
$this._lastFrameOccurrence = now - (delta % interval);
var response = {};
var factor = window.w.easing[$this.easing]($this._iteration, $this.duration);
for (var i in $this.x)
if ($this.x.hasOwnProperty(i))
response[i] = $this.x[i] + ($this.y[i] - $this.x[i]) * factor;
if ($this.onProgress instanceof Function)
$this.onProgress(response);
$this._iteration++;
if ($this._iteration > $this.duration)
if ($this.onComplete instanceof Function)
$this.onComplete();
};
if ($this._iteration <= $this.duration) {
$this._id = requestAnimationFrame(function() {
$this._draw();
});
} else {
cancelAnimationFrame($this._id);
};
}
};
animation._draw();
};
w.animate({
x: { opacity: 1 },
y: { opacity: 0 },
duration: 500,
onProgress: function(r) { console.log(r); },
onComplete: function() {}
});