Skip to content

Commit

Permalink
feat: Improve ticker by adding ranking & sort in add() method
Browse files Browse the repository at this point in the history
  • Loading branch information
willybrauner committed Dec 28, 2024
1 parent 95a9eb9 commit 2e6a59a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,6 @@
"path": "packages/interpol/dist/interpol.js",
"limit": "3.5 KB"
}
]
],
"packageManager": "[email protected]+sha512.6e2baf77d06b9362294152c851c4f278ede37ab1eba3a55fda317a4a17b209f4dbb973fb250a77abc463a341fcb1f17f17cfa24091c4eb319cda0d9b84278387"
}
14 changes: 8 additions & 6 deletions packages/interpol/src/core/Ticker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type Handler = (e: TickParams) => void
*/
export class Ticker {
#isRunning = false
#handlers: ((e: TickParams) => void)[]
#handlers: { handler: (e: TickParams) => void; rank: number }[]
#onUpdateObj: TickParams
#start: number
#time: number
Expand All @@ -39,12 +39,14 @@ export class Ticker {
this.#enable = false
}

public add(fn: Handler): void {
this.#handlers.push(fn)
public add(handler: (e: TickParams) => void, rank: number = 0): () => void {
this.#handlers.push({ handler, rank })
this.#handlers.sort((a, b) => a.rank - b.rank)
return () => this.remove(handler)
}

public remove(fn: Handler): void {
this.#handlers = this.#handlers.filter((h) => h !== fn)
public remove(handler: (e: TickParams) => void): void {
this.#handlers = this.#handlers.filter((obj) => obj.handler !== handler)
}

public play(): void {
Expand Down Expand Up @@ -81,7 +83,7 @@ export class Ticker {
this.#onUpdateObj.delta = this.#delta
this.#onUpdateObj.time = this.#time
this.#onUpdateObj.elapsed = this.#elapsed
for (const h of this.#handlers) h(this.#onUpdateObj)
for (const { handler } of this.#handlers) handler(this.#onUpdateObj)
}

#initEvents(): void {
Expand Down

0 comments on commit 2e6a59a

Please sign in to comment.