其总体目标是为某些文本实现类似打字的动画。
我循环遍历字符串的每个字母,并将其添加到 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/