Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active June 16, 2026 11:23
Show Gist options
  • Select an option

  • Save luizbills/70c148c5b9e6732ed59a4a2e6be171b4 to your computer and use it in GitHub Desktop.

Select an option

Save luizbills/70c148c5b9e6732ed59a4a2e6be171b4 to your computer and use it in GitHub Desktop.
Simple timer for litecanvas

Simple Timer

Litecanvas plugin to handle simple timers.

Usage

litecanvas()

function init() {
  // load the plugin
  use(pluginSimpleTimer)

  // example: alert every 2 seconds
  every(2, () => {
    alert('hello')
  })
  
  // example: alert just once after 5 seconds
  // note: return "false" to cancel a timer
  // note: "executed" stores the number of times the callback has been called
  every(5, (executed) => {
    if (executed > 0) return false
    alert('once')
  })
  
  // note: every(0, fn) runs every frame
  let frames = 0
  every(0, () => {
    frames += 1
  })
}

Live Demo

/**
* Simple Timer for Litecanvas
* @version 1.0.0
*/
function pluginSimpleTimer(engine) {
const ev = 'before:update'
function every(seconds, callback) {
// time accumulator
let acc = 0
// how many times the callback has been called
let i = 0
const handler = (dt) => {
acc += dt
if (acc >= seconds) {
acc -= seconds
// returns "false" in your callback to cancel the timer
if (false === callback(i++)) {
cancel()
}
}
}
const cancel = () => engine.unlisten(ev, handler)
engine.listen(ev, handler)
// also, every() returns a function to cancel the timer manually
return cancel
}
return { every }
}
@luizbills

Copy link
Copy Markdown
Author

For more advance timers use the Timers plugin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment