Skip to content

Instantly share code, notes, and snippets.

@bendc
Created September 1, 2017 08:57
Show Gist options
  • Select an option

  • Save bendc/e78d671aad87185d83c16c3898d03e68 to your computer and use it in GitHub Desktop.

Select an option

Save bendc/e78d671aad87185d83c16c3898d03e68 to your computer and use it in GitHub Desktop.

Revisions

  1. bendc created this gist Sep 1, 2017.
    32 changes: 32 additions & 0 deletions simulate-typing.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    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;
    };