So dropStart
is defined outside the drop
function and the drop
function is called multiple times since there is a call to requestAnimationFrame(drop)
also the drop function is called after dropStart is declared so there is likely to be a difference anyway since the code is not executed at the same time, how can we expect the timeDelta to be zero.
Also your code doesn't include this, but from the code in the snippet you were copying the requestAnimationFrame(drop) will cause this code to be called over and over again, so thats why the delta will be different each time. Every time the drop function is called it will instantiate a new date object and compare that to the one in global scope dropStart
. So with every call to drop()
we would expect the time difference to increase since we are travelling forwards in time.
Depending on what other code is going on I may or may not expect to see the first few calls to this drop function return less than 1000 ms, (I would guess not with most likely assumptions, although who knows without all the code). But after 1s (1000ms) I would then expect the condition (delta > 1000) to be true.
I think perhaps what you are missing here, is that this method is called over and over again due to the call to requestAnimationFrame(drop)
.
This answer is based on the assumption you didn't realise this method was being called multiple times.
From looking at the source code available at https://github.com/CodeExplainedRepo/Tetris-JavaScript/blob/master/tetris.js I can see that some events reset the dropStart time to Date.now()
- pushing "Up", "Left" or "Right" on the keyboard
function CONTROL(event){
if(event.keyCode == 37){
p.moveLeft();
dropStart = Date.now();
}else if(event.keyCode == 38){
p.rotate();
dropStart = Date.now();
}else if(event.keyCode == 39){
p.moveRight();
dropStart = Date.now();
}else if(event.keyCode == 40){
p.moveDown();
}
}
- when the delta is greater than a 1000 it resets itself anyway (here's a more complete version of the method from the source code
let dropStart = Date.now();
let gameOver = false;
function drop(){
let now = Date.now();
let delta = now - dropStart;
if(delta > 1000){
p.moveDown();
dropStart = Date.now();
}
if( !gameOver){
requestAnimationFrame(drop);
}
}
drop();