JSFiddle - React, Tailwind, and code Playground
by mcsf
HTML
We are <span id=s>here</span>
JavaScript
const words = ['here.', 'there.'];
let wid = 0;
const STEP_DURATION = 120;
const PAUSE_DURATION = 1000;
let lastTimestamp;
function clearText(timestamp) {
const delta = timestamp - lastTimestamp;
if (s.innerText) {
if (delta > STEP_DURATION) {
s.innerText = s.innerText.substring(0, s.innerText.length - 1);
lastTimestamp = timestamp;
}
requestAnimationFrame(clearText);
} else {
wid = (wid + 1) % words.length;
requestAnimationFrame(setText);
}
}
function setText(timestamp) {
const delta = timestamp - lastTimestamp;
const word = words[wid];
if (s.innerText != word) {
if (delta > STEP_DURATION) {
s.innerText = word.substring(0, s.innerText.length + 1);
lastTimestamp = timestamp;
}
requestAnimationFrame(setText);
} else {
if (delta > PAUSE_DURATION) {
requestAnimationFrame(clearText);
lastTimestamp = timestamp;
} else {
requestAnimationFrame(setText);
}
}
}
lastTimestamp = document.timeline.currentTime;
requestAnimationFrame(clearText);