Learn to Code via Tutorials on Repl.it!

← Back to all posts
Nodejs Typewrite effect
Coder100

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

Closing

Hope this made you hate js a bit more!

Voters
the2eyedcyclops
programmeruser
Coder100
Comments
hotnewtop
CodeLongAndPros

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

JWZ6
Coder100
JWZ6
codingjlu

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

CodeLongAndPros

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

DynamicSquid

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