Experiments >

Playing a tween in reverse

Experiment #3711th March, 2021by Joshua Nussbaum

After adding more functions to a tweened store. I realized I forgot to add reversing as well.

Reversing will be handy if you want to rewind a series of tweens, which I will need for the code animation project

To reverse a tween, the tween is paused at its current value, and then tweened back to its initial value:

store.reverse = async () => {
  // get current value
  const value = get(store)
  // compute how much was done so
  const percentageCompleted = (value - initial) / (store.lastSet - initial)
  // compute how much time was spent so far
  const completed = options.duration * percentageCompleted

  // pause at current value
  set(value, {duration: 0})
    
  // go back to the initial value
  // duration is the time spent so far
  return set(initial, {duration: completed})
}

Code

https://svelte.dev/repl/21e75022cc7a4acc95678447141fbee8?version=3.35.0

Demo

view all experiments

Stay tuned in

Learn how to add more experimentation to your workflow