Best way for simple game-loop in Javascript?

前端 未结 8 590
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 01:51

Is there a simple way to make a game loop in JavaScript? something like...

onTimerTick() {
  // update game state
}
8条回答
  •  盖世英雄少女心
    2020-12-14 02:34

    not sure how well this will work, but here is one method that uses a while loop and sleeps the thread. This is just an example, you can replace the game loop below with a better one, based on how you would do it in any other language. You can also find a better while loop here

    let gameRunning = false;
    
    async function runGameThread(){
        if(!gameRunning){
            gameRunning = true;
    
            // this function allows the thread to sleep (found this a long time ago on an old stack overflow post)
            const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
    
            // the game loop
            while(gameRunning){
                let start = new Date().getTime();
                gameUpdate();
                await sleep(start + 20 - new Date().getTime());
            }
    
        }
    }
    
    function stopGameThread(){
        while(gameRunning){
            try{
                gameRunning = false;
            }catch(e){}
        }
    }
    
    function gameUpdate(){
        // do stuff...
    }
    

提交回复
热议问题