Skip to content

Instantly share code, notes, and snippets.

@rodleviton
Forked from rik/simulateTyping.js
Created July 17, 2021 10:33
Show Gist options
  • Save rodleviton/ac1497e9c2b7333880ac141d141f232e to your computer and use it in GitHub Desktop.
Save rodleviton/ac1497e9c2b7333880ac141d141f232e to your computer and use it in GitHub Desktop.
Fake typing animation with async/await
async function nextFrame() {
return new Promise((resolve) => {
requestAnimationFrame(resolve)
})
}
async function randomDelay(min, max) {
const delay = Math.random() * (max - min) + min;
const startTime = performance.now()
while (performance.now() - startTime < delay) {
await nextFrame()
}
}
async function simulateTyping({string, target, min = 10, max = 80}) {
for (const letter of string) {
target.insertAdjacentText("beforeend", letter)
await randomDelay(min, max)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment