javascript - 在每次循环迭代上添加延迟

标签 javascript jquery for-loop setinterval

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

我的 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 循环的基本部分,或者不完全理解函数在其中的处理方式。

最佳答案

您没有将值传递给您内心的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);

关于javascript - 在每次循环迭代上添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26323489/

相关文章:

python - Pandas:尝试基于 for 循环删除行?

delphi - Delphi中For循环后的循环变量是什么?

javascript - 有没有办法在 react 中使用 leaflet.heat ?

javascript - 从长绳子中取出一段绳子

javascript - 无法打开所选对象的指向 url

javascript - 通过从 html 中提取图像来创建图像数组

javascript - 如何为ajax生成的图像设置绝对定位

javascript - 加载的 Ajax 页面表中的 Codeigniter 分页

javascript - 将日期列值与系统时钟进行比较

python - 加入单个 DataFrame 的两个唯一组合,将其转换为列名