Settimout在For循环内无法正常运行,很奇怪吗? [英] Settimout not working inside For loop, acting weird?
问题描述
我正在尝试使用javascript模拟打字机效果. 从理论上讲,它应该与我的代码一起工作:
Im trying to simulate a Typewriter effect with javascript. Theorically it should work with my code:
function TypeWriteToDoc(txt, id, x){
document.getElementById(id).innerHTML = document.getElementById(id).innerHTML + txt.charAt(x);
}
function TypeWrite(txt,id){
for (var i = 0; i < txt.length; i++){
setTimeout(function() {
TypeWriteToDoc(txt, id, i);
}, 1000*(i+1));
}
}
应该是这样,当我调用TypeWrite("example", "p_test");
时,应该在"p_test" html中写入"test"的每个字符.我认为问题不在我的代码上,因为当我不使用setTimeout
调用函数时,它的工作方式类似于以下代码:
That should be it, when i call TypeWrite("example", "p_test");
it should write each character of "test" in the "p_test" html. I think the problem its not on my code since when i call the function without using setTimeout
it works like in the code below:
function TypeWriteWithNoSettimeout(txt, id){
for (var i = 0; i < txt.lenght; i++){
TypeWriteToDoc(txt, id, i);}
}
推荐答案
这是var
在具有回调函数的for循环中的常见问题.
This is a common issue with var
in for-loops with callback functions.
最简单的解决方案?只需使用let
即可. let
在所有主要浏览器中均受支持.
The easiest solution? Just use let
instead. let
has support in all major browsers.
function TypeWrite(txt,id){
for (let i = 0; i < txt.length; i++){
setTimeout(function() {
TypeWriteToDoc(txt, id, i);
}, 1000*(i+1));
}
}
这篇关于Settimout在For循环内无法正常运行,很奇怪吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!