Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.
Asked Answered
S

1

11

Not sure what I'm doing wrong here...

window.requestAnimFrame = function(){
return (
    window.requestAnimationFrame       || 
    window.webkitRequestAnimationFrame || 
    window.mozRequestAnimationFrame    || 
    window.oRequestAnimationFrame      || 
    window.msRequestAnimationFrame     || 
    function(/* function */ callback){
        window.setTimeout(callback, 1000 / 60);
    }
);
}();

function animationSequence(elem, ind) {
    this.ind = ind;
    this.elem = elem;
    this.distance = 450;
    this.duration = 900;
    this.increment = 0;
    this.start = Math.abs(this.ind)*450;
    var requestId = requestAnimFrame(this.animate);
    this.move();

    this.move = function() {
        this.elem.style.left = this.start - this.increment + "px";
    }
    this.animate = function() {
        var self = this;
        this.move();
        this.increment += 5;
        if (this.increment >= 450) { 
            if (this.ind == 0) { console.log("true"); this.elem.style.left = "1350px" }
            cancelAnimFrame(requestId);
        }
    }
    // this.animate();
}
Stucker answered 26/2, 2014 at 10:55 Comment(1)
Did you try to place var requestId = requestAnimFrame(this.animate); below the this.animate function definition?Natural
C
35

Ok so help me out if I'm getting you wrong - is your problem that you have lost your reference to this within the animate method? i.e. you can't call this.move() or increment the increment?

If so try this-

 var requestId = requestAnimFrame(this.animate.bind(this));

See this answer about binding with requestAnimation callbacks here.

And this blog post on binding.

Update May 2019

If you can use ES6 you can employ an arrow function, which will maintain scope like this:

let requestId = requestAnimFrame(() => { this.animate(); });

Read about arrow functions here:

Blog post about arrow functions and the keyword this

Celebrant answered 16/7, 2014 at 13:55 Comment(2)
@Celebrant Thanks mate, it worked for me as well!Mukund
You saved my day mate. :)Morganatic

© 2022 - 2024 — McMap. All rights reserved.