I'm trying to animate text with javascript using an array with time intervals e.g. t te tex text, I want it to cycle from 0 to 21 and back and I'm not entirely sure how to do it. Any help is muchly appreciated!
General concept:
You need to update string output each tick with next value till full string will be visible. Tick interval defines how fast animation is.
One of possible realization below:
// Wait [ms] milliseconds
const Delay = ms => new Promise(r => setTimeout(r, ms));
// Main function
const main = async () => {
const p = document.querySelector('p');
// String you wanna animate
const targetText = 'Hello there!';
// Tick interval
const tick = 60;
// Iterating through string
for (let i = 1; i <= targetText.length; i++) {
// Set new value
p.innerHTML = (' '.repeat(targetText.length - i) + targetText.slice(-i));
// Wait for a next tick
await Delay(tick);
}
}
main();
p {
font-family: Monospace;
}
<p></p>
Here are:
- space will be visible inside of .innerHTML();
tick - interval between animation frames (in milliseconds);