0

When I run test.loop() it only executes once instead of at the expected rate. Any ideas what I can do to fix this?

"use strict;"

var test = function(options) {
    this.options = options;

    return this;
};

test.prototype = {
    'loop': function() {
        console.log('test');

        if (this !== window) {
            requestAnimationFrame(this.loop);
        }
    }
};

test.loop();
user2036108
  • 1,227
  • 1
  • 10
  • 12
  • 1
    This is unrelated but use `"use strict";` instead of `"use strict;"` or your code won't be parsed in strict mode. – howderek Mar 23 '15 at 19:02
  • Uh, if you are already doing such a `this !== window` check, you seem to know about the problem? – Bergi Mar 23 '15 at 19:19
  • I know it's something to do with the `this` scope but i can't wrap my head around the solution – user2036108 Mar 23 '15 at 19:22
  • I think Bergi overzealously closed as duplicate, because the OP already knew the subtleties of `this` but couldn't figure this specific instance out. Anyway, try this replacement line: `requestAnimationFrame(this.loop.bind(this));` – Katana314 Mar 23 '15 at 19:39

1 Answers1

0

test.loop() is not a function. test.prototype.loop is. And if you do:

var x = new test();
x.loop();

that will also work. See what you did wrong here? You forgot to use the new keyword to create a new object. Your code not only not works but it also produces a type error (undefined is not a function).

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Typed up my code snippet wrong, I am in fact using an instance of test and running the loop method of this instance. The problem of it not doing requestAnimationFrame still exists – user2036108 Mar 23 '15 at 19:18
  • @Adam I actually was about to point out the problem, but it definitely clashes with what the OP said - the loop "executes only once". So it's something else... – Katana314 Mar 23 '15 at 19:32