I am making a game in javascript and it is working properly but i have to make a condition that if 5sec have elapsed then increase the speed of the car by +1 and for that i first used setinterval and settimeout but that didnt worked out well because they werent precise so i am using date.now() and comparing it witht the latest time and check if the time elapsed is 5000 ms or not now the problem is once it gets in one condition it keeps running the same condition and not able to check it twice here is my code:-
function runGame() {
let car = document.querySelector('.myCar');
let road = gameArea.getBoundingClientRect();
aRect = car.getBoundingClientRect();
const d = new Date();
let ms = d.getSeconds();
// console.log(ms)
if (player.start) {
moveLines();
moveEnemy(car);
const startTime = Date.now();
var interval = 5000;
// get seconds
const start_time = Date.now()
//this is the place where the main problem starts
if (Math.round(Date.now() - player.time_value) == interval) {
player.speed += 1
player.score_var += 1
seconds = 0;
interval += 5000
} else {
// console.log(Math.round(startTime-Date.now()),'this is else')
console.log(player.time_value, 'this is the start time')
}
if (keys.ArrowUp && player.y > (road.top + 150)) {
player.y -= player.speed
}
if (keys.ArrowDown && player.y < (road.bottom - 85)) {
player.y += player.speed
}
if (keys.ArrowLeft && player.x > 0) {
player.x -= player.speed
}
if (keys.ArrowRight && player.x < (road.width - 50)) {
player.x += player.speed
}
car.style.top = player.y + "px";
car.style.left = player.x + "px";
window.requestAnimationFrame(runGame);
score.innerText = "Score: " + player.score + "\nSpeed: " + player.speed;
}
}
here player.time_value is static which generates when the game initializes (its in another function)