Fake typing animation
This file contains 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
const trackTime = timing => { | |
const now = performance.now(); | |
if (!timing.startTime) timing.startTime = now; | |
const elapsed = now - timing.startTime; | |
const {duration} = timing; | |
if (duration != null && duration <= elapsed) timing.startTime = null; | |
return elapsed; | |
}; | |
const delay = (callback, duration) => { | |
const timing = {duration}; | |
const tick = () => | |
trackTime(timing) < duration ? requestAnimationFrame(tick) : callback(); | |
tick(); | |
}; | |
const random = (min, max) => | |
Math.random() * (max - min) + min; | |
const simulateTyping = ({ | |
string, target, callback, min = 10, max = 80, iterator = string[Symbol.iterator]() | |
}) => { | |
const {value} = iterator.next(); | |
if (value) | |
delay(() => { | |
target.insertAdjacentText("beforeend", value); | |
simulateTyping({string, target, callback, min, max, iterator}); | |
}, random(min, max)); | |
else | |
callback && callback(); | |
return target; | |
}; |
Author
bendc
commented
Sep 1, 2017
I've implemented it with async/await in https://gist.github.com/rik/56638f4efdd808c9af0e1a43b297d1a2. I find it simpler to understand and tweak.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment