Last active
August 18, 2020 00:08
-
-
Save FeMaffezzolli/72a47a0f20776ad59ab7bb5afb9f693a to your computer and use it in GitHub Desktop.
State Changer Based on Sequential Timeouts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If using with React, be careful with changing state of unmounted components.