Learn to Code via Tutorials on Repl.it!

← Back to all posts
Nodejs Typewrite effect

Typewriter effect

Here is something I hear a lot, nodejs is bad for terminal games! The thing is, it is. Imagine having to install an npm library just to get user input, and then have to learn how to make a typewriter effect! But it does teach you a lot -- in my opinion -- about asynchronous coding and being on top of everything.

First solution

In many programming languages, you would just loop through the text and write it out.
So that's what we try:

Nothing printed! Why? Remember, as with all typewriter effects, we must flush the buffer, which we can't do, because it is nodejs, and flushing is a blocking operation, which is a big no-no.

Second Solution

Instead, we combat this cleverly with some recursion.

How does this work? Well, the second function passed in is called when the terminal gets flushed. When we do that, we just do a setTimeout as our 'sleep' function, and then write the second character by slicing part of the text. It needs to stop somewhere, and it stops once the text is length > 1, because there is only one character left to print.

Asynchronous version

Of course, we must also add the usage of await :D


Hope this made you hate js a bit more!


If only I could downvote...
You brought the angst of teletype output and combined it with the pain of javascript programming.


@CodeLongAndPros lololololol but you can't because he's CODER100 lol


@codingjlu "I'm delisting this, seeing as it's JavaScript and a typewriter effect, it can't stand"


@CodeLongAndPros Agreed, this is the ugliest thing I have ever seen. JS used to make effects for the console??