Skip to content Skip to sidebar Skip to footer

Settimout Not Working Inside For Loop, Acting Weird?

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 = do

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

Solution 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.

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

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

Post a Comment for "Settimout Not Working Inside For Loop, Acting Weird?"