TypeWritter Effect - Vanilla JS

TypeWritter Effect - Vanilla JS

There comes a time when you want to do something cool like a typewriter on a web page. There are multiple ways to accomplish it, but today let me show you the vanilla JS way!

The Algorithm

First, we have to initialize a list of strings that we want to type and erase in a loop. The idea is to start from the first character of the first line. We keep adding characters, till we reach the end. Note that we have added + 5 here to stall for a few more cycles before we start erasing. Then we start removing characters, this time 2 at a time! This creates an effect of slow typing and fast erase. Once we reach the beginning of the string, we reset the direction and move on to the next item in the array. Finally, once we reach the end, we start over from the first item in the array.

Performance

I switched to the performance tab and recorded the run for about 10 seconds. The scripting time is approximately 0.002%.

image.png

Advantage over CSS

I have seen some CSS based solutions, but they have a dependency on the number of characters and work for only one string. This allows you to work with multiple strings in a loop and independent of the string length. If you want to tinker with the speed, just change the timeout value.


Love what you see? Follow me or subscribe to the newsletter to stay updated when I post more cool stuff!

Did you find this article valuable?

Support Ones and Zeros by becoming a sponsor. Any amount is appreciated!