Home > Software engineering >  Javascript simple game loop - how to interval?
Javascript simple game loop - how to interval?

Time:04-01

I have a simple game loop that goes like this:

function update(progress){
    //do something each second

    //do something else twice per second

    //do something else each two seconds
}

function draw() {
  //code here...
}

function gameLoop(timestamp) {

  update(progress)
  draw()
  
  var progress = (timestamp - lastRender)
  lastRender = timestamp

  window.requestAnimationFrame(gameLoop)
}

var lastRender = 0
window.requestAnimationFrame(gameLoop)

How can I make sure to execute some actions into the update function each helf second, second, or two seconds?

Thank you

CodePudding user response:

If you want to define the interval, you'll need to use setInterval. requestAnimationFrame will only update based on the refresh rate of the screen so you cannot define your own interval with this. setInterval has lots of downsides though, so it is recommended to sync up the interval with the refresh rate using something like this:

let doUpdate = false
setInterval(() => doUpdate = true), 1000)
const render = () => {
  if (doUpdate) {
    // your code
    doUpdate = false
  }
}
window.requestAnimationFrame(render)

CodePudding user response:

setInterval(function {
  //code that happends every second goes here
}, 1000);
  • Related