Pause a game loop that uses 'requestAnimationFrame()'

时间:2015-12-14 17:57:57

标签: javascript loops

I'm trying to add the Pause functionality to a game loop I have:

GameLoop = {

  //Insert more members here if needed

  run : function(options) {

    var now,
        dt       = 0,
        //last     = timestamp(),
        last     = Date.now(),
        slow     = options.slow || 1, // slow motion scaling factor
        step     = 1 / options.fps || 60,
        slowStep = slow * step,
        update   = options.update,
        render   = options.render;


    function frame() {
        //now = timestamp();
        now = Date.now();
        dt = dt + Math.min(1, (now - last) / 1000);
        while(dt > slowStep) {
            dt = dt - slowStep;
            update(step);
        }
        render(dt / slow);
        last = now;
        requestAnimationFrame(frame, options.canvas);
    }
    requestAnimationFrame(frame);

  }

};

I've used some documentation and tutorials to get to this structure and I already have a game that seems to work perfect with it.

Is there a way I can add a function like 'pause' so it stops, then I can resume it whenever I want and continue normaly?

Let me know if you need more code or any additional iformation, thanks!

1 个答案:

答案 0 :(得分:3)

Either you don't call the handler recursively in case of stop, or you can cancel requested function by cancelAnimationFrame().