Skip to content
Advertisement

How to wait for a function, which calls itself recursively with setTimeout, to complete?

I am new to Javascript and currently working on a website, that changes how it looks by itself over time.

One part of this page is a “Typewriter”, that writes out a text letter by letter. This is the code for this Typewriter:

JavaScript

Now I want to wait for the typewriter-function to finish with its text before doing another change to let’s say my background-color.

JavaScript

To my understanding, the setTimeout makes my typewriter async, so if I do it as in the example above the third line of code will run as soon as the typewriter hits the first setTimeout.

I tried to realize this with the async/await terms and promises. But even after I resolve the promise, my “runThis” function won’t continue after the typewriter finishes.

JavaScript

Can you please help me figure out what’s wrong here? Thank you very much

Advertisement

Answer

You can wrap the setTimeout in a promise. This will allow you to use the async/await syntax to express the intention of your code more clearly, almost as if it was running synchronously.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement