Skip to content

Commit

Permalink
deploy: 360db9c
Browse files Browse the repository at this point in the history
  • Loading branch information
ninjamar committed Nov 17, 2024
1 parent 75a44c0 commit 99a52ac
Showing 1 changed file with 19 additions and 23 deletions.
42 changes: 19 additions & 23 deletions projects/2tetris/tetris.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,38 +127,34 @@ COLORS = [
];


/**
* Self adjusting interval
* @param {Function} callback - called every interval, takes one parameter, drift > interval
* @param {Number} interval - interval in milliseconds
*/
function adjustingInterval(callback, interval){
function unbackloggedAdjustingInterval(callback, interval){
// https://stackoverflow.com/a/29972322/
let isBacklogged = false;

let active = [];
let expected = Date.now() + interval;
setTimeout(step, interval)
function step(){
let drift = Date.now() - expected;
callback(drift > interval);
if (drift > interval && active.length > 0){
// When the tab isn't focused, the intervals will be backlogged
// We don't want this to happen, so clear all the previous interval
active.forEach(timeout => clearTimeout(timeout));
active = [];
isBacklogged = true;
} else {
isBacklogged = false;
}
if (!isBacklogged){
callback();
}
expected += interval;
setTimeout(step, Math.max(0, interval - drift));
let id = setTimeout(step, Math.max(0, interval - drift));
active.push(id);
}
}


/**
* Self adjusting interval that pauses when tab is out of focus
* @param {Function} callback - called every interval, takes one parameter, drift > interval
* @param {Number} interval - interval in milliseconds
*/
function pausingAdjustingInterval(callback, interval){
return adjustingInterval((bad) => {
if (!bad || document.hasFocus()){
callback(bad);
}
}, interval);
}


/**
* Get a random color
* @returns {String} *
Expand Down Expand Up @@ -561,7 +557,7 @@ function TetrisGameHandler(...args){
loop();
*/
game.draw();
pausingAdjustingInterval(() => {
unbackloggedAdjustingInterval(() => {
game.receiveEvent("softDrop");
// window.requestAnimationFrame(game.draw);
}, 500);
Expand Down

0 comments on commit 99a52ac

Please sign in to comment.