1

I have recently started working off a javascript Tetris template and i've got stuck trying to implement a pause feature. I am trying to create a window.onkeydown function so that when a button is clicked the game will pause and also toggle to continue once clicked again.

Here is a snippet of my code

function get(id) {
    return document.getElementById(id);
};

function hide(id) {
    get(id).style.visibility = 'hidden';
};

function show(id) {
    get(id).style.visibility = null;
};

function html(id, html) {
    get(id).innerHTML = html;
};

function timestamp() {
    return new Date().getTime();
};

function random(min, max) {
    return (min + (Math.random() * (max - min)));
};

function randomChoice(choices) {
    return choices[Math.round(random(0, choices.length - 1))];
};

if (!window.requestAnimationFrame) { // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function (callback, element) {
            window.setTimeout(callback, 1000 / 60);
        }

}

var isPaused = true;

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

function Start() {
    if (isPaused) {
        Update();
    }

    requestAnimFrame(Start);
}

window.onkeydown = function () {
    isPaused = !isPaused; // flips the pause state

};

Can anyone point me in the right direction?

1 Answers1

1

You would have to keep a reference on the setTimeout. Like,

module.timeout = setTimeout(callback, 1000/60);

So when you flip the isPaused, clear both timeouts and restart them later when you're pausing them.

clearTimeout(module.timeout)
Zlatko
  • 18,936
  • 14
  • 70
  • 123