无尽的控制台日志,javascript不会离开函数requestAnimationFrame

时间:2014-12-11 21:27:03

标签: javascript canvas recursion requestanimationframe

我在控制台中得到无尽的'渲染'......为什么会这样?我想不出来! :(我大部分时间都在这一天。你们能看出问题所在吗?

控制台:

turnEvent
render
10 times render
Infunction: 150.458ms
6534 and counting times render

代码:

var turnEvent = function turnEvent(AnX, AnY) {
    var first = true;
    console.time('Infunction');
    var lengd = rects.length, i;
    one30 = 10,
    one40 = 10,  
    one301 = false, 
    one401 = false;
    for (i = 0; i < lengd; i += 1) {
        if (collides([rects[i]], AnX, AnY)) {
            var rightBox = rects[i];
            var rectangle = rects2[i];
        }
    }
    console.log("turnEvent");
    rounded_rect(rectangle.x, rectangle.y, 90, 110, 10, 'black', 'black');
    function render() {
        console.log("render"); <----------- ENDLESS CONSOLE LOGS

        -----some canvas drawings here------
        .......
       ----if and else conditions----
        if (one301 && one401) {
            rounded_rect(rectangle.x, rectangle.y, 90, 110, 10, null, 'black');
            console.timeEnd('Infunction');
        }
    }
    (function animloop(){
        requestAnimationFrame(animloop);
        render();
    })();
}

1 个答案:

答案 0 :(得分:2)

因为requestAnimatinoFrame将调用animloop,它将执行另一个执行animloop等等的requestAnimationFrame调用,它是一个递归动作。

您需要在animloop中创建一个不调用requestAnimationFrame

的条件
(function animloop(){
    if(someConditionMet){
       //return without executing another requestAnimationFrame
       return;
    }
    requestAnimationFrame(animloop);
    render();
})();