简体   繁体   English

创建一个在JavaScript中逐步显示输出的函数

[英]Creating a function that shows the output step by step in JavaScript

Im trying this and the code works fine. 我试图这样做,代码工作正常。 The page process the code and then shows me the result, but I dont want this. 该页面处理代码,然后向我显示结果,但我不希望这样做。 I want the page show step by step the for process, first print A, wait some time and then show AB, wait again and show ABC, etc... 我希望页面逐步显示for过程,首先打印A,等待一段时间,然后显示AB,再次等待,然后显示ABC,等等。

window.onload = function() {
  var parrafo = document.createElement("p");
  var frase = "ABCDEFGHIJ";
  var spl = frase.split("");
  document.body.appendChild(parrafo);
  for(i in spl){
    var contenido = document.createTextNode(spl[i]);
      parrafo.appendChild(contenido);
      sleep(100);
    }
  }

function sleep(ms) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > ms){
      break;
    }
  }
}

You can use the setTimeout() function and wrap the for loop in that. 您可以使用setTimeout()函数并在其中包装for loop For example, 例如,

printStuff(spl, i) {
    var contenido = document.createTextNode(spl[i]);
      parrafo.appendChild(contenido);
      setTimeout(printStuff(spl, i++), 1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM