Reputation: 1415
Well basically I tried to make a typewriter script from scratch, for my little terminal web app junkie xD
Well, I've got this JavaScript thingy:
var str = "dude";
var num = 1000;
for (var i = 0, len = str.length; i < len; i++) {
var num = num + 100;
var dude = str[i];
setTimeout('document.getElementById("guide").innerHTML +=dude;', num);
}
which obviously writes to a div
with the ID
guide
, "d" "u" "d" "e" in 100 milisecond intervals, but guess what ?
It doesn't do that !!
NOW what it DOES do it print "e" as many times as they are characters in the string, dude!!
:|
Thank you,
I'm probably super stupid
but I'd love a fix!
Thanks in advance!
Upvotes: 1
Views: 432
Reputation: 476
I wrote a small function that accept 2 parameters: the text and the time :
function defiredWriteText(text,time, index){
if(index === null || index === undefined) {
index=0;
}
setTimeout(function (){
var dude = text[index];
document.getElementById("guide").innerHTML += dude;
if(index < text.length-1)
defiredWriteText(text, time, ++index);
}, time)
}
sample: http://jsfiddle.net/3e3yx/
Upvotes: 1
Reputation: 2623
You might want to call a function in setTimeout like the following:
var str = "dude";
var num = 1000;
for (var i = 0, len = str.length; i < len; i++) {
var num = num + 100;
var dude = str[i];
setTimeout(function() {
document.getElementById("guide").innerHTML +=dude;
}, num);
}
or
var str = "dude";
var num = 1000;
for (var i = 0, len = str.length; i < len; i++) {
var num = num + 100;
var dude = str[i];
setTimeout(changeHtml, num);
}
function changeHtml() {
document.getElementById("guide").innerHTML +=dude;
}
If you want a more precise 100 millisecond interval you might want to use setInterval
var myInterval = setInterval(changeHtml, 100);
var len = str.length;
var current = 0;
function changeHtml() {
if(current < len) {
document.getElementById("guide").innerHTML +=str[current];
}
else {
clearInterval(myInterval);
}
current++;
}
Upvotes: 1