Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fake typing animation
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;
};
@bendc

This comment has been minimized.

Copy link
Owner Author

commented Sep 1, 2017

// Example

simulateTyping({
  string: "hello world",
  target: document.querySelector(".fake-input"),
  callback: () => console.log("done")
});
@rik

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.