I am trying to make a game loop in javascript where an event happens every x amount of time, and that time gets shorter with each loop.
This is the code I’ve tried using:
const begin = document.getElementById("startbtn")
begin.onclick = start;
//Game loop
function start() {
console.log("test");
let i = 1000;
while (i>0) {
loop(i);
i = i - 100;
}
function loop(i){
setTimeout(function(){
console.log("adsafsd");
}, 5 * i);
}
}
But it just repeats at the same interval, and finishes in about 5 seconds after 10 loops.
I imagined that the setTimeout in the loop function would get shorter, since it takes 5 times the i variable, which is subtracted by 100 every loop.
3
Answers
You could use
async/await
and wrapsetTimeout
into a promise to make the code more manageable:If you don’t want to swap to async like the other (really good) answer:
Your current code creates all timeouts almost simultaneously, each with a delay that’s decreasing by 100ms with each iteration. However, setTimeout works asynchronously, so it doesn’t wait for the previous timeout to finish before setting up the next one, which means all timeouts are setup virtually at the same time. Therefore, they end almost together, just with minor delays relative to each other.
You should set up each next timeout after the previous one has finished. You could accomplish this by using recursion in your loop function:
Using your example:
But I think the best model for this question will be: