在每次循环迭代时添加延迟

时间:2014-10-12 09:04:03

标签: javascript jquery for-loop setinterval

这样做的总体目标是为某些文本实现类似打字的动画。 我循环遍历字符串的每个字母,并在FOR循环中使用setTimeout将每个字母之间的延迟添加到DOM中。

我的HTML -

<h1 id="name">Hello World!</h1>

我的Javascript -

$(document).ready(function(){
    var typeText = $("#name").html();
    var textLength = typeText.length;
    $("#name").empty();

    for(i=0;i<textLength;i++) {
        (function(i){
            console.log("first function being fired!");
            setTimeout(function(i){
                console.log("setTimeout function being fired!");
                console.log(i);
                var letter = typeText.substring(i,i+1);
                console.log(letter);
                $("#name").append(letter);
            },5000);
        })();
    }
});

我没有收到任何错误,但我首先记录了12个“第一个功能被解雇!”的帐户,延迟5秒,然后是12个帐户:

setTimeout function being fired<br />
undefined<br />
[line-break]

我认为我缺少FOR循环的基本部分,或者不完全理解函数在其中的处理方式。

2 个答案:

答案 0 :(得分:1)

您没有将值传递给内部i

$(document).ready(function(){
    var typeText = $("#name").html();
    var textLength = typeText.length;
    $("#name").empty();

    for(i=0;i<textLength;i++) {
        (function(i){
            console.log("first function being fired!");
            setTimeout(function(){ // not necessary here
                console.log("setTimeout function being fired!");
                console.log(i);
                var letter = typeText.substring(i,i+1);
                console.log(letter);
                $("#name").append(letter);
            },5000);
        })(i); // pass here
    }
});

如果你想让每个人在之前的5秒后开火,而不是只等待5秒并完成所有这些,你可以像这样设置超时:

setTimeout(function(){
// ...
}, 5000 * i);

答案 1 :(得分:0)

我相信你一直在寻找这样的行为:

&#13;
&#13;
function doLetter(totaltext, i) {
  console.log("function being fired on text",totaltext,"at position",i);
  var letter = totaltext.substring(i, i + 1);
  console.log(letter);
  $("#name").append(letter);
  if(i<totaltext.length-1){
    setTimeout(doLetter.bind(null,totaltext,i+1), 500);
  }
}

$(document).ready(function() {
  var typeText = $("#name").html();
  $("#name").empty();
  doLetter(typeText,0);

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

<body>
  <p id="name">Hello World!</p>
</body>
&#13;
&#13;
&#13;

整个交易不是立即运行所有字母处理程序。运行一个,让它知道它正在处理的原始文本。一旦完成了它的字母,它将为下一个字母设置超时。注意&#34;绑定&#34; :)

相关问题