Search code examples
javascripthtmldelayed-execution

Code runs simultaneously (typewriter effect)


I'm running into an issue with my code. I'm executing this function below multiple times in a row. I want the code to execute the second time I call the 'defiredWriteText'-function, after the first call is finished writing its string. This is the code:

function defiredWriteText(text,time, index, p_id){
        const newP = document.createElement("p");
        newP.id = p_id;
        document.getElementById("container").appendChild(newP);
        
        if(index === null || index === undefined) {
                index=0;
        }
            setTimeout(function (){
                    var txt = text[index];
                    document.getElementById(p_id).innerHTML += txt;
                    if(index < text.length-1)
                        defiredWriteText(text, time, ++index,p_id);
        }, time)
    }



//This first
var str = "Hello stranger! What's your name?"
var num = 100;
var p_id = "p_1";
defiredWriteText(str,num,0,p_id);

//Then this                             
var str = "Oooooh! It's you..."
var num = 100;
var p_id = "p_2";
defiredWriteText(str,num,0,p_id);

//This at last
var str = "..."
var num = 175;
var p_id = "p_2";
defiredWriteText(str,num,0,p_id);
<div id="container"></div>

I do not fully understand, why this all runs at once. Any help is appreciated


Solution

  • Have it return a Promise which you can then await (or use then if you so prefer)

    function defiredWriteText(text,time, index, p_id){
            const newP = document.createElement("p");
            newP.id = p_id;
            document.getElementById("container").appendChild(newP);
            
            return new Promise(resolve => {
              const appendText = (index) => {
                if(index === null || index === undefined) {
                      index=0;
                }
                setTimeout(function (){
                          var txt = text[index];
                          document.getElementById(p_id).innerHTML += txt;
                          if(index < text.length-1)
                              appendText(++index);
                          else
                            resolve();
                }, time)
              }
              appendText();
            })
        }
    
    (async function() {
      //This first
      var str = "Hello stranger! What's your name?"
      var num = 100;
      var p_id = "p_1";
      await defiredWriteText(str,num,0,p_id);
    
      //Then this                             
      var str = "Oooooh! It's you..."
      var num = 100;
      var p_id = "p_2";
      await defiredWriteText(str,num,0,p_id);
    
      //This at last
      var str = "..."
      var num = 175;
      var p_id = "p_2";
      await defiredWriteText(str,num,0,p_id);
    })()
    <div id="container"></div>