Skip to content

Instantly share code, notes, and snippets.

@nandordudas
Created January 15, 2025 15:59
Show Gist options
  • Save nandordudas/14c199965bbcf9de8670609dcbea2069 to your computer and use it in GitHub Desktop.
Save nandordudas/14c199965bbcf9de8670609dcbea2069 to your computer and use it in GitHub Desktop.
;((options) => {
const {
ONE_SECOND,
COLOR_LENGTH,
DURATION_MULTIPLIER,
RED_LIKE,
GREEN_LIKE,
BLUE_LIKE,
} = options
const ColorUtils = {
get randomHex(): string {
return crypto.randomUUID().slice(-1 * COLOR_LENGTH)
},
get randomOpacity(): string {
return Math.random().toFixed(3)
},
createColorString(hex: string, opacity: string): string {
return `rgb(from #${hex} ${RED_LIKE} ${GREEN_LIKE} ${BLUE_LIKE} / ${opacity})`
},
} as const
const AnimationState = {
intervalId: null as ReturnType<typeof globalThis.setInterval> | null,
isRunning: false,
start(): void {
if (this.isRunning)
return
this.isRunning = true
this.intervalId = globalThis.setInterval(() => {
const { createColorString, randomHex, randomOpacity } = ColorUtils
const backgroundColor = createColorString(randomHex, randomOpacity)
try {
document.body.style.backgroundColor = backgroundColor
// eslint-disable-next-line no-console
console.table({
generated: backgroundColor,
applied: document.body.style.backgroundColor,
})
}
catch (error) {
console.error('Failed to apply background color:', error)
}
}, ONE_SECOND)
globalThis.setTimeout(this.stop.bind(this), DURATION_MULTIPLIER * ONE_SECOND)
},
stop(): void {
if (!this.isRunning)
return
if (this.intervalId !== null)
globalThis.clearInterval(this.intervalId)
this.intervalId = null
this.isRunning = false
},
}
AnimationState.start()
})({
ONE_SECOND: 1_000,
DURATION_MULTIPLIER: 10,
COLOR_LENGTH: 6,
RED_LIKE: 255, // 0-255 or r
GREEN_LIKE: 'g', // 0-255 or g
BLUE_LIKE: 0, // 0-255 or b
} as const)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment