15

I'm having problem finding out how I can use requestAnimationFrame in a class.

This code is working fine:

window.onload = function () {
    var width = 20;
    function animation() {
        width++;
        var element = document.getElementById("box");
        element.style.width = width + "px";
        requestAnimationFrame(animation);
    }
    requestAnimationFrame(animation);
};

But when I try putting it into a class, I don't get any result.

class Animation{
    width: number = 20;

    constructor() {
        requestAnimationFrame(this.loop);
    }
    loop() {
        this.width++;
        var element = document.getElementById("box");
        element.style.width = this.width + "px";
        requestAnimationFrame(this.loop);
    }
}
window.onload = function () {
    var animation = new Animation();
};

Could someone tell me what's wrong here?

Tc_
  • 505
  • 1
  • 6
  • 15
  • i would say it is a bad idea to have the requestAnimFrame in the constructor (since a constructor can be called/initialised under various cases), better put it in a method like .initLoop or sth. For the actual question you will have to bind the this.loop method to the "this" object. i.e this.loop.bind(this) so "this" is available and correctly assigned when the loop method will be called – Nikos M. Mar 06 '15 at 22:52
  • 1
    meaning: "**requestAnimationFrame(this.loop.bind(this));**" – Nikos M. Mar 06 '15 at 22:53
  • @NikosM. I fully agree. I only did it to shorten the example. Didn't knew about `bind(this)` , I just read up on it, and know it works. =) Thanks! – Tc_ Mar 06 '15 at 23:09

1 Answers1

27

requestAnimationFrame(this.loop); If you are passing someone else a function that they are going to call use an arrow i.e requestAnimationFrame(()=>this.loop()); or loop = () => {

More : https://www.youtube.com/watch?v=tvocUcbCupA

basarat
  • 261,912
  • 58
  • 460
  • 511