Settimout not working inside For loop, acting weird?

情到浓时终转凉″ 提交于 2019-12-11 14:44:18

问题


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));
  }
}

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);}
}

回答1:


This is a common issue with var in for-loops with callback functions.

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));
  }
}



回答2:


Similar to the previous response but rather than appending original text along with div.innerHtml, I adjusted it to be just the text char which simulates more of a typewriter feel. To increase the delay, I multiplied the index with 1000 rather than adding it since the larger increments are more visible.

function TypeWriteToDoc(txt, id, i) {
  setTimeout(function() {
    var div = document.getElementById(id)
    div.innerHTML +=txt.charAt(i)
  }, 1000 * (i))
 }

function TypeWrite(txt,id){
  for (var i = 0; i < txt.length; i++) {
    TypeWriteToDoc(txt, id, i)
  }
 }
 
TypeWrite('example', 'p_test')
<div id="p_test"></div>


来源:https://stackoverflow.com/questions/46992706/settimout-not-working-inside-for-loop-acting-weird

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!