I tried to look up and suck in most of the information about optimizing this operation and this is what I came up with. As it's pretty much core of the game, I really would like to have it performant as much as I can. I would appreciate if someone can take a look at this and possibly find weak spots.
Note: I am using Browserify, hence that
module.exports. Don't get confused, it is supposed to run in the browser.
module.exports = (tickModule, app) -> # Function to retrieve current timestamp, hopefully using window.performance object getTime = if (perf = window.performance)? then -> perf.now() else Date.now # Store the reference so there is no need for scope lookup in every tick raf = window.requestAnimationFrame # Indicates if module is running running = false # Holds identifier for cancelAnimationFrame call requestId = null # Timestamp of the last run of the tick previous = 0 # Run the tick loop tick = -> return unless running # Request frame and store identifier requestId = raf tick # Retrieve current timestamp timestamp = getTime() # Calculate number of seconds from last tick delta = (timestamp - previous) * 0.001 # Store the timestamp for the next round previous = timestamp # Emit event with delta app.land.emit 'tick', delta, timestamp # Start ticking when module start tickModule.addInitializer -> previous = getTime() running = true tick() # Stop ticking when module stops tickModule.addFinalizer -> running = false window.cancelAnimationFrame requestId
I am thinking about removing that
running, since I am not really planning to stop the ticking once it starts. It was made merely like nice gesture, but it's not that useful for the game I suppose.