Skip to content

Commit 5998d6f

Browse files
authored
Merge pull request #79 from crashmax-dev/graceful-stop
feat: added `waitStop` #76
2 parents 87498fb + 4dbd360 commit 5998d6f

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,11 @@ Stop fireworks.\
265265
Type: `boolean`\
266266
Default: `false`
267267

268+
#### `.waitStop(dispose)`
269+
Asynchronous stopping of the fireworks.\
270+
Type: `boolean`\
271+
Default: `false`
272+
268273
#### `.pause()`
269274
Start/stop fireworks.
270275

examples/basic/src/index.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,21 @@ import './style.css'
33

44
const app = document.querySelector<HTMLDivElement>('#app')!
55
const fireworks = new Fireworks(app)
6-
fireworks.start()
6+
7+
const button = document.createElement('button')
8+
button.textContent = 'Start'
9+
button.style.position = 'absolute'
10+
button.style.zIndex = '999'
11+
button.addEventListener('click', () => {
12+
fireworks.start()
13+
stopFireworks(fireworks)
14+
})
15+
16+
document.body.appendChild(button)
17+
18+
async function stopFireworks(fireworks: Fireworks) {
19+
console.time()
20+
await new Promise((resolve) => setTimeout(resolve, 2000))
21+
await fireworks.waitStop()
22+
console.timeEnd()
23+
}

packages/fireworks-js/src/fireworks.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export class Fireworks {
2626
private mouse: Mouse
2727
private traces: Trace[] = []
2828
private explosions: Explosion[] = []
29+
private waitStopRaf: (() => void) | null
2930

3031
constructor(
3132
container: Element | HTMLCanvasElement,
@@ -77,6 +78,24 @@ export class Fireworks {
7778
}
7879
}
7980

81+
async waitStop(dispose?: boolean): Promise<void> {
82+
if (!this.running) return
83+
84+
return new Promise<void>((resolve) => {
85+
this.waitStopRaf = () => {
86+
if (!this.waitStopRaf) return
87+
requestAnimationFrame(this.waitStopRaf)
88+
if (!this.traces.length && !this.explosions.length) {
89+
this.waitStopRaf = null
90+
this.stop(dispose)
91+
resolve()
92+
}
93+
}
94+
95+
this.waitStopRaf()
96+
})
97+
}
98+
8099
pause(): void {
81100
this.running = !this.running
82101
if (this.running) {
@@ -155,6 +174,8 @@ export class Fireworks {
155174
}
156175

157176
private initTrace(): void {
177+
if (this.waitStopRaf) return
178+
158179
const {
159180
hue,
160181
delay,

0 commit comments

Comments
 (0)