javascript - Using setTimeout to print a string char by char -


i'm trying simple, it's not working , can't figure out why not. trying write text div such text appears 1 character @ time; sort of scene in matrix.

var message = document.getelementbyid("message");   function writemessage(string) {     message.innerhtml = string.charat(0);     (var = 1; < string.length; i++) {       window.settimeout(function() {message.innerhtml+=string.charat(i);},1000);     }   }   writemessage("hello world"); 

to see code's inaction in action, see jsfiddle. can tell, displays first character, if settimeout not executing function @ all.

the function pass settimeout executed after loop completes i variable equal string.length when executes. try solve storing i temporary variable, or using iife. however, function instances you've registered settimeout end executing @ approximately same time, won't see animation.

perhaps try using setinterval, this:

function writemessage(string) {     var = 0, intervalid;     intervalid = window.setinterval(function() {         message.innerhtml += string.charat(i++);         if (i > string.length)              window.clearinterval(intervalid);     }, 100);  }  writemessage("hello world"); 

demonstration


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -