代码同时运行(打字机效果)

Code runs simultaneously (typewriter effect)

我 运行 我的代码有问题。我在下面连续多次执行此功能。我希望代码在我调用 'defiredWriteText'-函数时第二次执行,在第一次调用完成其字符串的写入之后。这是代码:

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>

我不完全明白,为什么这一切都同时运行。感谢任何帮助

把它 return 一个 Promise 然后你可以 await (或者如果你愿意的话使用 then

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>