admin管理员组

文章数量:1417691

I have js file where I am using requestAnimationFrame(). I know that argument should be callback function. I think that my argument is callback function, but errors cames in js console:

TypeError: Argument 1 of Window.requestAnimationFrame is not an object.

file.js:

function screen(){
     console.log("it works!")
}

function fun(word){
    if (word === 'tree'){
        screen()
    }
window.requestAnimationFrame(fun("tree"));

everything works nice. I use it in my large project and everything works as I want, but I don't know why I have errors in js console

I have js file where I am using requestAnimationFrame(). I know that argument should be callback function. I think that my argument is callback function, but errors cames in js console:

TypeError: Argument 1 of Window.requestAnimationFrame is not an object.

file.js:

function screen(){
     console.log("it works!")
}

function fun(word){
    if (word === 'tree'){
        screen()
    }
window.requestAnimationFrame(fun("tree"));

everything works nice. I use it in my large project and everything works as I want, but I don't know why I have errors in js console

Share Improve this question asked Jan 3, 2018 at 22:55 gongarekgongarek 1,0441 gold badge11 silver badges20 bronze badges 1
  • this isnt the way how you utilize requestAnimationframe() it is used to make sure that your animations run smoothly if you are using javascript for animations instead of css and it should be inside the function fun() and the call to function fun() should be after the declaration of the function, what are you using this function for? – Muhammad Omer Aslam Commented Jan 3, 2018 at 23:38
Add a ment  | 

2 Answers 2

Reset to default 5

You pass a result of the execution of fun function to the requestAnimationFrame, that's why you got an error (because it's returns an undefined).

Correct way to do it:

function screen(){
     console.log("it works!")
}

function fun(word){
    if (word === 'tree'){
        screen()
    }
}
window.requestAnimationFrame(fun.bind(window, "tree"));

More information about bind you can find in documentation.

A mon way to handle this kind of thing is to wrap your call to fun("tree") inside an anonymous function, which bees the callback that requestAnimationFrame can use:

function screen(){
     console.log("it works!")
}

function fun(word){
    if (word === 'tree'){
        screen()
    }
}
window.requestAnimationFrame(function () { fun("tree"); });

This differs from your code in that you are passing in the result of calling the fun function with the parameter "tree". As fun doesn't return anything that result is undefined. It's as if you did

var x = fun("tree"); // x is undefined
window.requestAnimationFrame(x);

本文标签: javascriptcallback function as argument of windowrequestAnimationFrame()Stack Overflow