Skip to content

Instantly share code, notes, and snippets.

@FeMaffezzolli
Last active August 18, 2020 00:08
Show Gist options
  • Save FeMaffezzolli/72a47a0f20776ad59ab7bb5afb9f693a to your computer and use it in GitHub Desktop.
Save FeMaffezzolli/72a47a0f20776ad59ab7bb5afb9f693a to your computer and use it in GitHub Desktop.
State Changer Based on Sequential Timeouts
/**
* In this example shows an implementation of handling the change of audio volume
* based on sequentials timeout functions.
*
*/
let volume = 0
function setVolume(volume: number) { console.log(volume) }
interface stateChangerProps {
timing: number;
targetState: number;
currentState: number;
stateSetter(volume: number): void;
}
function stateChanger(options: stateChangerProps) {
const { timing, targetState, currentState, stateSetter } = options
if (targetState === currentState) throw new Error('1001')
if (timing === 0) throw new Error('1002')
const STEPS_PER_SECOND = 30
const fadeEffectSteps = STEPS_PER_SECOND * (timing / 1000)
const delayForEachStep = timing / fadeEffectSteps
const changeForEachStep = (targetState - currentState) / fadeEffectSteps
for (let i = 0; i <= fadeEffectSteps; i++) {
const delay = delayForEachStep * i
const stepState = changeForEachStep * i
setTimeout(() => stateSetter(stepState), delay)
}
}
stateChanger({
timing: 800,
currentState: 0,
targetState: 70,
stateSetter: setVolume
})
@FeMaffezzolli
Copy link
Author

If using with React, be careful with changing state of unmounted components.

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