0.0.1-s11 • Published 2 years ago

@nomorejalapenos/ticker v0.0.1-s11

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Ticker

a game loop with some methods to easily manage callbacks inside it.

Usage

Import

import ticker, { TickListener } from '@nomorejalapenos/ticker'

Create callback

  • t - current time
  • dt - time elapsed since last frame
const tick: TickListener = (t: number, dt: number) => {
  // ...
}

Add callback to the loop

if before that there were no callbacks in the loop, it starts running.\ You can specify the position of the callback in the queue as the second\ argument, by default they are queued in the order they were added.

const removeCallback = ticker.add(tick, -10)

Remove callback from the loop

if there are no more callbacks in the loop, it stops.

ticker.remove(tick)

or

removeCallback()

Remove callback from the loop after delay

the same as the remove method. but you can specify after\ what amount of time the callback will be removed from the loop.

ticker.removeAfterDelay(tick, {
  delay: 2000,
  afterRemove: () => {
    console.log('callback successfully removed from the loop')
  },
})

Example

import ticker from '@nomorejalapenos/ticker'

const el = document.createElement('div')

el.style.cssText = `
  position: fixed;
  top: calc(50% - 10vmin);
  left: calc(50% - 10vmin);
  width: 20vmin;
  height: 20vmin;
  background-color: tomato;
`

document.body.appendChild(el)

const removeCallback = ticker.add((t) => {
  t *= 0.001
  el.style.transform = `translateX(${Math.cos(t) * innerWidth * 0.1}px)`
})

addEventListener('click', () => {
  removeCallback()
})