Skip to content

Instantly share code, notes, and snippets.

@bendc
Created September 1, 2017 08:57
Show Gist options
  • Save bendc/e78d671aad87185d83c16c3898d03e68 to your computer and use it in GitHub Desktop.
Save bendc/e78d671aad87185d83c16c3898d03e68 to your computer and use it in GitHub Desktop.
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
Copy link
Author

bendc commented Sep 1, 2017

// Example

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

@rik
Copy link

rik 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